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:()=> {默认值}

相关推荐
计算机魔术师25 分钟前
NVIDIA 以 129.3 亿美元收购 Hugging Face
前端
平头哥技术团队26 分钟前
Day 01 | 用 HTML 写第一个网页:双击就能在浏览器打开
前端
weixin_422555421 小时前
el-menu子菜单点击就被激活,恢复之前的激活状态
javascript·vue.js·elementui
计算机魔术师1 小时前
两年翻45倍!英伟达靠买买买建成千亿投资帝国
前端
paopaokaka_luck1 小时前
基于springboot3+vue3的精准扶贫管理系统(AI 问答、ECharts 图形化分析)
前端·人工智能·echarts
l1m0_2 小时前
智能电动自行车管理后台实战:AI生成页面与React组件化技巧
前端·react.js·ui·ai·设计
Patrick_Wilson2 小时前
为什么gitlab的MR会默认有一个merge commit
前端·git·gitlab
en.en..2 小时前
Linux mmap 内存映射深度解析:基于帧缓冲 /dev/fb0
java·服务器·前端
后台模板学习3 小时前
从0到1用Vite构建电商订单系统前端性能优化方案
前端
Wang's Blog3 小时前
Vibe Coding一人即团队系列58: HTML演示文稿自动生成
前端·人工智能·html