VUE--Props(子级接收父级传来的数据)

准备工作

创建两个组件 src/components/Parent.vue 和 src/components/Child.vue,其中Parent.vue是Child.vue的父级组件

将Parent.vue在App.vue中注入,将Child.vue在Parent.vue中注入

App.vue:

<!--html代码(模块展示 显示在页面上的内容)-->
<template>
    <Parent />
</template>

<!--vue代码-->
<script >
    import Parent from "./components/Parent.vue";
    export default {
        components:{
            Parent
        }
    }
</script>

Parent.vue:

<template>
    <h2>Parent</h2>
    <Child />
</template>

<script>
    import Child from "./Child.vue";
    export default {
        data(){
            return{

            }
        },
        components:{
            Child
        }
    }
</script>

Child.vue:

<template>
    <h2>Child</h2>
</template>

<script>
    export default {
        data(){
            return{

            }
        }
    }
</script>

具体实现

props可传递不同类型的值

Parent.vue:

<template>
    <h2>Parent</h2>
    <div>
        <Child :msg="msg" :age="age" :names="names" :userInfo="userInfo"/>
    </div>
</template>

<script>
    import Child from "./Child.vue";
    export default {
        data(){
            return{
                msg:"通过父级传给子级的信息", // 传递字符串 String
                age:20, // 传递数字 Number
                names:["Jack","Jan","John"], //传递数组 Array
                userInfo:{ // 传递对象 Object
                    name:"May",
                    age: 22
                }

            }
        },
        components:{
            Child
        }
    }
</script>

 

通过v-bind绑定数据,将值传递给子级组件使用

Child.vue:

<template>
    <h2>Child</h2>
    <p>父级传来的字符串:{{ msg }}</p>
    <p>父级传来的数字:{{ age }}</p>
    <p>父级传来的数组:</p>
    <ur>
        <li v-for="(item,index) in names" :key="index">{{ item }}</li>
    </ur>
    <p>父级传来的对象:</p>
    <p>{{ userInfo.name }}</p>
    <p>{{ userInfo.age }}</p>
</template>

<script>
    export default {
        data(){
            return{

            }
        },
        // 接收父级传来的数据
        props:["msg","age","names","userInfo"]
    }
</script>

props的校验--type

props传递默认值--default

注:对于String和Number类型的值,可以直接使用default,而对于数组和对象,必须采用函数的方法进行返回

props的必传项--required

当父级未给子级传递子级所想要的必传项时,控制台将会抛出警告,而页面不会出现任何异常

注:

props对父级传来的值仅可读,不可对其传来的值进行修改

 

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值