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、浏览器效果如下:
标签:TypeScript,name,age,id,Persons,10px,默认值,withDefaults From: https://www.cnblogs.com/tianpan2019/p/18365584