$attrs
包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。
在跨层级组件中,爷孙之间的通信,如果父级组件不需要,而孙级组件需要,就可以使用 $attrs
// 爷级
<parent-1 msg="hello attrs" msg1="arrts 2"></parent-1>
// 父级
<!--
在父级用 v-bind="$attrs" 可以将祖先组件绑定的属性传到子级 (不包括style、class、以及在 props 中使用的数据)
-->
<children-3 v-bind="$attrs"></children-3>
// 子级
<div>不在props中声明的属性,会在这里显示 <br/> {{ $attrs }}</div>
$listeners
包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。
在跨层级组件中,爷孙之间的通信也可以使用 $listeners
// 爷级
<parent-1 @myFoo="myFoo"></parent-1>
// 父级
<children-3 v-on="$listeners"></children-3>
// 子级
<button @click="handleFoo">触发爷级事件</button>
handleFoo() {
this.$emit("myFoo");
}