023、Vue3+TypeScript基礎,使用defineProps限制父傳子的資料型別,並用v-for顯示

像一棵海草海草海草發表於2024-08-18

01、index.js程式碼如下:

// 定義一個介面,用於限制person物件的具體屬性
export interface PersonInter {
    id: string;
    name: string;
    age: number;
}

export type Persons = Array<PersonInter>;

02、App.vue程式碼如下:

<template>
  <div class="app">
    <h2>App.Vue</h2>
    <!--    使用了ref來獲取子元件的屬性-->
    <Person :a1='person' :list1="personList"/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue'
import type {PersonInter, Persons} from "@/view";

let person: PersonInter = {
  id: 'a0',
  name: 'Joker',
  age: 999,
}

let personList: Persons = [
  {
    id: 'a001',
    name: '張三',
    age: 18,
  },
  {
    id: 'a002',
    name: '李四',
    age: 19,
  }
]
</script>

<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

03、person程式碼如下:

<template>
  <div class="person">
    <h2>{{ a1 }}</h2>
    <ul>
      <!--      一定要加key,如果後端實在沒有唯一值,那麼才能用index-->
      <li v-for="(item, index) in list1" :key="item.id">
        {{ index }}--{{ item.name }}--{{ item.age }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import {defineProps} from 'vue'
import type {PersonInter, Persons} from "@/view";

defineProps<{
  a1: PersonInter;
  list1: Persons;
}>()

</script>

<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }
}
</style>

04、效果如下;

05、效果如下:

相關文章