从“追求尽量不出错”,到正视“出错是必然”的转变|

如此而已~~~

园龄:3年3个月粉丝:0关注:12

props的使用

props的使用

父组件通过props给子组件

传递基础上获取并添加限制条件

​ 注意:一些属性必须加 : 使其是计算属性,否则传递的是字符串

​ 注意:defineProps 一般defineXxx函数是宏函数可以不用引入,但是我在使用的时候需要引入,可能是语法检查或者其他

ts约束文件:
//限制单个 定义一个接口,用于限制person对象的具体属性
export interface PersonConstraint {
id:string,
name:string,
age:number,
// x?:number, //x? 表示可选的
}
//限制一组 一个自定义类型
export type PersonListConstraint = Array<PersonConstraint>
// export type PersonListConstraint = PersonConstraint[]
App父组件
<template>
<div class="app">
<!-- 通过':' 即 v-bind 后,我们可以F12发现对应 "" 中的是表达式,并计算了 -->
<!-- <h2 a="1+1" :b="1+1" c="x" :d="x"></h2> -->
<Person v-bind:list="personList"/>
</div>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue';
import { reactive } from 'vue';
import {type PersonConstraint, type PersonListConstraint} from '@/types'
let personList = reactive<PersonListConstraint>([
{ id: '1212', name: '张三', age: 60 },
{ id: '1213', name: '李四', age: 61 },
{ id: '1214', name: '王五', age: 62 }
]);
let x = 9;
</script>
Person子组件
<template>
<div class="person">
<ul>
<!-- 注意 key 前要写 : 不然不是计算的id,一直都是使用第一个数据的id -->
<li v-for="person in list" :key="person.id">
{{person.name}} -- {{person.age}}
</li>
</ul>
</div>
</template>
<script setup lang="ts" name="Person">
import {defineProps, withDefaults} from 'vue'
import {type PersonListConstraint } from '@/types';
//接收
// let list = defineProps(['list']) //接收a,同时将props保存起来
//接收+限制类型
// let list = defineProps<{list:PersonListConstraint}>() //这里将这个值赋值给一个变量 不用 变量.list
// console.log(list.list);
//接收 + 限制类型 + 限制必要性(?) + 指定默认值(withDefaults函数)
withDefaults(defineProps<{list?:PersonListConstraint}>(), {
list: () => [{id: '1212', name: '康师傅', age: 19}]
})
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px; /* 盒子阴影 */
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
</style>

本文作者:如此而已~~~

本文链接:https://www.cnblogs.com/fragmentary/p/18626691

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   如此而已~~~  阅读(14)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起