当前位置: 首页> 教育> 锐评 > Vue3【十七】props的作用和组件之间的传值限定类型和默认值

Vue3【十七】props的作用和组件之间的传值限定类型和默认值

时间:2025/7/16 14:42:18来源:https://blog.csdn.net/gixome/article/details/139592530 浏览次数:0次

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>
关键字:Vue3【十七】props的作用和组件之间的传值限定类型和默认值

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: