Vue3---基础7(Props)

props,用于给子组件传递父组件的值的方法

代码示例:

父组件

javascript 复制代码
<template>
    <Text1 :list="personList"/>
</template>

<script lang="ts" setup namae="App">
    import Text1 from './components/text2.vue'
    import { reactive } from 'vue'
    import { type Persons }  from '@/types'

    let personList = reactive<Persons>([
        {id: '19821220', name:'张杰', age: 22},
        {id: '19822024', name:'Jason', age: 25},
    ])

</script>

我在父组件内,定义了数据 personList 数组,并在子组件上绑定了该数据

子组件

javascript 复制代码
<template>
    <div class="person">
        <h2>{{ list }}</h2>
        <ul>
            <li v-for="item in list" :key="item.id">姓名: {{ item.name }}; 年龄:{{ item.age }}</li>
        </ul>
    </div>
</template>

<script lang="ts" setup name="text2">
    import {defineProps, withDefaults} from 'vue'
    import { type Person } from '@/type'

    // 只接收list
    // defineProps(['list'])

    // 接收list + 限制类型
    // defineProps<{list:Person}>()

    // 接收list + 限制类型 + 限制必要性 + 制定默认值
    withDefaults(defineProps<{list:Person}>(), {
        list:()=> [{id: 111222, name: '默认姓名', age: 18}]
    })

    // 接收list  同时将 props 保存起来
    // let x = defineProps(['a', 'list'])
    // console.log('x', x)
    
</script>

有四种方法去使用

第一种

只接收值

第二种

接收值,同时保持该值

第三种

接收值的时候使用<>,限制类型

第四种

接收值的时候,限制类型,限制必要性和设置默认值

defineProps

是用来在子组件内去接收父组件的值

withDefaults

在接收父组件的值时,给该值设置默认值

需要用回调函数去返回该默认值,不能直接设置

xxx:()=> {默认值}

相关推荐
hoLzwEge2 分钟前
团队协作的隐藏利器:.vscode 完全指南
前端·前端框架
labixiong4 分钟前
TypeScript 7.0 编译器用 Go 重写,速度暴增10倍——背后到底做了什么?
前端·javascript·go
WaywardOne6 分钟前
Flutter组件化方案(AI总结)
前端·flutter·ai编程
玉宇夕落6 分钟前
原子化编程”:Tailwind CSS 核心原理
前端
是小李呀11 分钟前
解决“Error: The project seems to require yarn but it‘s not installed”报错
前端
weedsfly12 分钟前
一个电商价格计算案例,带你学会前端开发中的责任链模式
前端·javascript·面试
__sjfzllv___13 分钟前
在职前端Leader学习/转行 AI Agent -DAY10
前端
沉迷学习日益消瘦17 分钟前
8 UI 组件库与设计系统:Token 驱动 + 暗色模式 + 4 种主题色
前端
CodeSheep32 分钟前
有这4个迹象,你就该离职了!
前端·后端·程序员
用户0595401744633 分钟前
把大模型记忆回归测试从手工检查换成 Playwright+VCR,误判率从 40% 降到 0
前端·css