vue中的v-bind = “$attrs”和 v-bind="$props"的使用

534 阅读1分钟

v-bind = "$attrs"

主要用于组件之间的隔代传值。在一个组件中,通过this.$attrs传递当前组件身上绑定的属性,(不包含组件内已经通过prop接收的属性)

//GrandFather.vue祖父组件
<template>
    <div>
        <father :name='name' :age='age'></father>
    </div>
</template>
<script>
    name:'zhangsan';
    age:18
</script>
//Father.vue祖父组件
<template>
    <div>
       <!-- 通过v-bind='$attrs'将祖父组件传递给父组件的数据,全部传递给子组件--!>
        <son v-bind='$attrs'></son>
    </div>
</template>
<script>
    //此处不声明prop接收祖父组件传递给father的数据
</script>

这个时候我们在去访问父组件和子组件的this.$attrs的时候,可以看到祖父组件的传递的值

接下来我们对父组件进行一下修改

//Father.vue祖父组件
<template>
    <div>
       <!-- 通过v-bind='$attrs'将祖父组件传递给父组件的数据,全部传递给儿子组件--!>
        <son v-bind='$attrs'></son>
    </div>
</template>
<script>
    //此处声明prop接收祖父组件传递的数据
    props:['name']
</script>

在控制台打印出来的时候,我们就可以看到,父组件中this.$attrs中少了一个name属性,相反,在props多了一个name属性。子组件中的this.$attrs里面也是少了一个name属性,只有一个age

v-bind="$props"

将父组件的所有props接受的参数,传递给子组件,子组件需要在props:{}黎曼定义要接收的props 如果使用v-bind="$props"来传递数据会怎么样呢?

我们对父组件再进行修改

//Father.vue祖父组件
<template>
    <div>
       <!-- 通过v-bind='$props'将祖父组件传递给父组件的数据,全部传递给儿子组件--!>
         <son v-bind='$props'></son>
    </div>
</template>
<script>
    //此处声明prop接收祖父组件传递的数据
    props:['name']
</script>

在控制台输出,我们会发现,如果父组件通过props接收了name属性,通过v-bind='$props'传递给子组件,只有这一个name属性,如果父组件没有通过props接收祖父组件的数据,那么子组件的this.$attrs就是空--没有任何数据。

总结

v-bind = “$attrs”v-bind="$props"其实就是往子组件传递的参数不同,一个传递的是vm.attrs,另一个则是传递的vm.props。而组件的attrs就是除了组件声明的props之外的其他绑定在本组件的属性