inheritAttrs、$attrs和$listeners使用场景:
组件传值,尤其是祖孙组件有跨度的传值。
(1)inheritAttrs
属性说明:
说明比较晦涩。
组件传值一般是通过props传值的。inheritAttrs默认值为true,true的意思是将父组件中除了props外的属性添加到子组件的根节点上(说明,即使设置为true,子组件仍然可以通过$attr获取到props意外的属性)。示例代码:
grandpaDom.vue:
fatherDom.vue:
------------fatherDom-------------
attrs:{
{$attrs}}foo:{
{foo}}------------fatherDom-------------
说明:grandpaDom.vue将foo和coo属性都放在fatherDom.vue上,但是fatherDom.vue的props值接收了foo,因此grandpaDom的coo属性显示在了fatherDom的根节点上。即:
接着将inheritAttrs:false后(请将fatherDom.vue添加inheritAttrs:false),coo属性就不会显示在fatherDom根节点上了。但是怎么获取到coo呢?
这时就通过$attrs获取到到coo。
接着看孙组件childDom.vue:
------------childDom-------------
coo:{
{coo}}------------childDom-------------
孙组件childDom.vue就可以通过props接收到coo属性了。
好,以上是总祖父--父亲--儿子向下传递值。
那怎么儿子-父亲--祖父传递数据呢呢?
父亲组件使用$传递。
最终祖父组件收到孙组件的事件了。