那么,在多层嵌套组件中,顶层组件和最底层组件之间如何进行数据传递和事件触发呢?比如,A 组件引用了 B 组件,而 B 组件又引用了 C 组件,那么怎么在 A 中将数据传给 C ;在 C 中,怎么触发 A 中的方法呢?这就是 $attrs 和 $listeners 的作用了。
$attrs
$attrs 是一个内置属性,指父组件传递的、除了自己定义的 props 属性之外的所有属性。例如 A 组件引用 B 组件,并为其绑定了三个属性 foo、coo、coo1:
复制代码
B 组件【child-dom】中定义的属性为 props: ['foo', 'coo1'] 那么在 B 组件中打印 $attrs,就是除了 props 之外的属性 coo 。此时,B 又引用了组件 C 并向其传递了一个属性 coo :
复制代码
而 C 组件【child-dom-child 】中定义了 props: ['coo', 'coo1'],此时在 C 组件中打印的$attrs是空的。学习所参考的项目中,需要在 B 组件中将 $attrs 绑定给 C ,但是测试发现,去掉这个绑定操作,C 中默认也是有$attrs 属性,也可以得到父组件的值。
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "coo1"复制代码