目录
一、v-bind=“$attrs“
二、v-bind="$props"
三、总结
一、v-bind=“$attrs“
主要用于组件之间的隔代传值。 在一个组件里,this.$attr传递当前组件身上绑定的所有属性(不考虑声明了组件内prop的话)
这么说是不是稍微有点绕?让我们看看例子。
// GrandFather.vue 祖父组件 <template> <div> <father-page :name="testName" :data-name="dataName" /> </div> </template> <script> ... testName = 'Test101'; ... dataName = 'dataName' </script>
复制
// FatherPage.vue 父组件 <template> <div> <child-page v-bind="$attrs" /> </div> </template> <script> // 不声明props(不接收祖父组件传过来的数据) </script>
复制
这时候ChildPage.vue和FatherPage.vue 组件内的 this.$attrs
如果我们修改一下 FatherPage.vue 组件
// FatherPage.vue 父组件 <template> <div> <child-page v-bind="$attrs" /> </div> </template> <script> ... props:['testName'] </script>
复制
可以看见FatherPage.vue的 this.$attrs 属性里少了testName,而props多了testName
ChildPage.vue接收到的this.$attrs也只有dataName了。
如果使用的是 v-bind="$props" 呢?咱们继续往下看
二、v-bind="$props"
将父组件的所有props下发给它的子组件,子组件需要在其props:{} 中定义要接受的props。
如果将父组件传递给子组件的方式改为
<grand-son v-bind="$props"></grand-son>
复制
如果在 FatherPage.vue 的props中接收的是testName,那么通过v-bind="$props" 传递给ChildPage.vue 的 this.$attrs 就是testName,如果在 FatherPage.vue中没有声明props,那么在ChildPage.vue 中的this.$attrs 就是空
三、总结
v-bind="$props"和v-bind="$attrs" 其实就是往子组件里传的参数不同,一个传的是vm.props一个传的是vm.attrs。而组件的attrs其实就是除了本组件声明的prop属性之外的其他绑定在本组件上的属性(可以是vue的动态绑定属性或者name type这些原生/自定义属性)