我始终对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>