01、index.ts程式碼如下:
// 定義一個介面,用於限制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> <!--<Person :a1='person' :list1="personList"/>--> <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.vue程式碼如下:
<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, withDefaults} from 'vue' import type {PersonInter, Persons} from "@/view"; // 主頁面沒有資料,所以需要預設值 withDefaults( defineProps<{ a1: PersonInter; list1: Persons; }>(), { a1: () => { return { id: 'id_default', name: 'name_default', age: 0, } }, list1: () => [ { id: 'a001', name: '張三', age: 18, } ] } ) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
04、效果如下:
05、瀏覽器效果如下: