Props用于父组件向子组件传值
定义类型
javascript
// 定义一个接口,用来限制Teacher的属性
export interface Teacher {
name: string;
age: number;
gender: string;
}
export type teacherList = Teacher[];
// 一个自定义类型
export type Teachers = Array<Teacher>;
父组件
html
<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import { reactive, ref } from 'vue'
import { type teacherList } from '@/types';
let personList = reactive<teacherList>([
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 25, gender: '男' },
{ name: '王五', age: 30, gender: '男' }
])
</script>
<template>
<div class="container">
<!-- <Person a="哈哈" :list="personList"/> -->
// 不传list,让子组件显示默认数据
<Person a="哈哈" />
</div>
</template>
<style scoped>
.container {
display: flex;
height: 100vh; /* 使容器占满整个屏幕高度 */
}
</style>
子组件
html
<script lang="ts" setup name="Person">
import { type teacherList } from '@/types';
// let x = defineProps(['a', 'list'])
// 要先声明才能打印
// console.log(x.a)
// 只接受
// defineProps(['a', 'list'])
// 接受+限制
// defineProps<{list:teacherList}>()
// 接受+限制+限制必要性+默认值
withDefaults(defineProps<{list?:teacherList}>(),
{
// 默认值,这里的默认值也得是teacherList类型,而且是个函数
list:() => [
{name:'张三',age:20, gender:'男'},
{name:'李四',age:25, gender:'女'}
]
}
)
</script>
<template>
<div class="person">
<!-- <h1>{{ a }}</h1> -->
<ul>
<li v-for="item in list" :key="item.name">{{ item.name }} - {{ item.age }}</li>
</ul>
</div>
</template>
<style scoped>
</style>