defineProps-只接收
- 父:要有数据
let personList = reactive<personArr>(
[
{id:'qqq1',name:'aaa',age:10,gender:'F'},
{id:'qqq2',name:'vvv',age:30,gender:'F'},
{id:'qqq3',name:'ddd',age:20,gender:'F',x:1}
]
)
- 父:要在子标签中写入
<template>
<Person :list="personList"/>
</template>
- 整体如下
// 父组件
<template>
<Person :list="personList"/>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue';
import { reactive } from 'vue';
import { type personArr } from '@/types';
let personList = reactive<personArr>(
[
{id:'qqq1',name:'aaa',age:10,gender:'F'},
{id:'qqq2',name:'vvv',age:30,gender:'F'},
{id:'qqq3',name:'ddd',age:20,gender:'F',x:1}
]
)
</script>
- 子:使用defineProps接收数据
<script lang="ts" setup name="Person">
import { defineProps } from 'vue';
defineProps(['list'])
// let x = defineProps(['personList']) -- 可使用x记录下来父组件传过来的数据
</script>
- 子:使用数据
<template>
<div class="person">
<ul>
<li v-for="item in list" :key="item.id">{{ item.name }} -- {{ item.age }}</li>
</ul>
</div>
</template>
defineProps-接收 + 限制类型
- 修改子:
<script lang="ts" setup name="Person">
import { defineProps } from 'vue';
import { type personArr } from '@/types';
// defineProps(['list'])
// let x = defineProps(['personList']) -- 可使用x记录下来父组件传过来的数据
defineProps<{list:personArr}>()
</script>
- 如果父传输类型错误,会报错
defineProps-接收 + 限制类型 + 限制必要性(数据可传可不传) + 默认值指定(不传时展示默认值-withDefaults)
- 子:修改为(页面能展示,但是报错)
<script lang="ts" setup name="Person">
import { defineProps,withDefaults } from 'vue';
import { type personArr } from '@/types';
// defineProps(['list'])
// let x = defineProps(['personList']) -- 可使用x记录下来父组件传过来的数据
withDefaults(defineProps<{list?:personArr}>(),{
list:[{id:'qqq1',name:'aaa',age:10,gender:'F'}]
})
</script>
- 父:去掉传的数据
<!-- 原代码
<template>
<Person :list="personList"/>
</template>
-->
<template>
<Person />
</template>
- 修改子中的报错:修改为一个函数:
withDefaults(defineProps<{list?:personArr}>(),{
list:()=>[{id:'qqq1',name:'aaa',age:10,gender:'F'}]
})
标签:vue,name,gender,age,组件,import,009,id,defineProps
From: https://www.cnblogs.com/ayubene/p/18081673