我一直对v-bind=“$attrs”和v-bind=“$props” 两个属性分不清楚,今天学习并总结了一下。
官方定义:
包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。
在网上看了前辈的解释:
当子组件没有声明或者说没有接收父组件传下来的prop属性时,那么父组件传下来的prop属性会被保存在子组件的vm.$attrs属性上。
这里指的父组件的意思是比较广泛的,是可以跨层级的父组件;假如子组件是下例的grandson组件,那么father组件和son组件均是它的父组件。
代码截图:
我在父组件中使用v-bind写了三个属性,在子组件中有一个props1是作为props接收的,其它两个没写在props里面说明就是放在了$attrs属性上,在created里面打印this.$attrs,得到{attrs1: 1234567,attrs2: "接收父组件里的数据"}。
我一共写了三个组件:父组件,子组件,孙子组件。在子组件中写入v-bind="$attrs",则孙子组件也可以接收父组件的子组件attrs属性了。
如果孙子组件需要同时接收$attrs, $props,则在子组件写入v-bind="[$attrs, $props]"即可。
下面是完整的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<h3>父组件</h3>
<child v-bind:attrs2="attrs2" v-bind:attrs1="1234567" v-bind:props1="`我是props1`"></child>
</div>
<script src="http://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
<script>
// 孙子组件-----------------------------------------------------------------------------------------------
Vue.component('grandchild', {
template:
`
<div>
<h3>孙子组件</h3>
attrs接收:{{$attrs.attrs1}}
<br/>
attrs接收:{{$attrs.attrs2}}
<br/>
props接收:{{props1}}
</div>
`,
name: 'grandchild',
inheritattrs: false,
props: {
props1: String
},
created() {
console.log(this.$attrs, '$attrs')
},
})
// 子组件-----------------------------------------------------------------------------------------------
Vue.component('child', {
template:
`
<div>
<h3>子组件</h3>
attrs接收:{{$attrs.attrs1}}
<br/>
attrs接收:{{$attrs.attrs2}}
<br/>
props接收:{{props1}}
<grandchild v-on="$listeners" v-bind="[$attrs, $props]"></grandchild>
</div>
`,
name: 'child',
inheritattrs: false,
props: {
props1: String
},
})
// 父组件-----------------------------------------------------------------------------------------------
new Vue({
name: 'parent',
// inheritattrs: false,
el: '#app',
data() {
return {
attrs2: '接收父组件里数据'
}
},
})
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。