Vue3【十七】props的作用和组件之间的传值限定类型和默认值
Vue3【十七】props的作用和组件之间的传值限定类型和默认值
父组件传值给子组件 多个值传递
传值限定类型和
默认值
实例截图
目录结构
代码
person.vue
<template><div class="person"><p>Props的使用</p> <!-- <p>父组件传值给子组件</p> --><p>父组件传值给子组件:a:{{ a }} b: {{ b }}</p><h3>list: {{ list }}</h3><h4><ul><li v-for="w in list" :key="w.id" >{{ w.name }} -- {{ w.age }}</li></ul></h4><!-- <h3 a ="1+1" :b="1+1" :d='a' > 测试标签计算代码:a ="1+1" :b="1+1" :d=a </h3> --></div>
</template><script lang="ts" setup namwe="Person">
import { type PersonInter,type Persons } from '@/types';
import { reactive } from 'vue';// 等同于 Array<PersonInter>
// let personList3 = reactive<Persons>([
// {id: 1,name: '白娘子',age: 10008,},
// {id: 2,name: '法海',age: 10900,},
// {id: 3,name: '文曲星',age: 20,x: 111},
// ])// difine开头的函数 可以直接使用 接受 a,b,list同时将props保存到x 中
let x = defineProps(['a','b','list'])
console.log(x)// 只接收list
// defineProps(['list'])// 接受 list 并限制类型
// defineProps<{ list: Persons }>()// 接受list 限制类型 限制必要性 指定默认值
// withDefaults(
// defineProps<{ list?: Persons}>(),
// {
// list:()=>[
// {id:1,name:'小青',age:11000}
// ]
// }// )
</script><style scoped>
.person {background-color: #ff9e4f;box-shadow: 0 0 10px;border-radius: 30px;padding: 30px;
}button {margin: 0 10px;padding: 0 5px;box-shadow: 0 0 5px;;
}
</style>
index.ts
// 定义一个接口,用于限制person对象的具体属性
export interface PersonInter {id: number,name: string,age: number,x?: number, //? 表示可选属性
}// 一个自定义类型
// export type Persons = Array<PersonInter>
// 等同于
export type Persons = PersonInter[]
app.vue
<template><div class="app"><h1>你好世界! 我是App根组件</h1><Person a="经验值+200" b="魔法药水+100" :list="personList" /><!-- <Person /> --></div>
</template><script lang="ts" setup name="App"">
import Person from './components/Person.vue'
import {reactive} from 'vue'
import {Persons} from './types'let personList = reactive<Persons>([{id: 1,name: '白娘子',age: 10008,},{id: 2,name: '法海',age: 10900,},{id: 3,name: '文曲星',age: 20,x: 111},
])
</script><style scoped>
.app {background-color: #4fffbb;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;
}
</style>