$attrs
- 只读
- 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。
- 优点在于避免传多个参数时,都要声明到props的麻烦,可直接通过$attrs.xx展示数据。
// hello.vue
<diy-component @click="getClick" msg1="通过props" msg2="不通过props"></diy-component>
//diyComponent.vue
<template>
<div>
传递:{{$attrs}}
</div>
</template>
<script>
export default {
name: 'diyComponent',
props: ['msg1'] //通过props传递值
}
</script>
页面显示为
$listeners
- 只读
- 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。
- 简单说就是将父组件的所有监听器(监听事件),通过v-on="$listeners" 绑到目标子组件;使其子组件可以更方便的调用父组件的相关函数。
//hello.vue
<diy-component ref="ttx" @click="clickMe"></diy-component>
// clickMe () {
// console.log('来自爸爸的点击')
// }
//diyComponent.vue
<template>
<div>
//点击子组件的button,调用的是组件根元素的clickMe方法
<el-button v-on="$listeners">click</el-button>
</div>
</template>
inheritAttrs(补充)
- 如果你不希望组件的根元素继承特性,你可以在组件的选项中设置 inheritAttrs: false。
- 通过实例属性 $attrs 可以让这些特性生效,且可以通过 v-bind 显性的绑定到非根元素上。
//hello.vue
<diy-component ref="ttx" @click="clickMe" msg1="通过props" msg2="不通过props" placeholder="nothing"></diy-component>
//diyComponent.vue
<template>
<div>
<div v-bind="$attrs">
传递:{{$attrs}}
</div>
<el-button v-on="$listeners">click</el-button>
</div>
</template>
<script>
export default {
name: 'diyComponent',
props: ['msg1'],
inheritAttrs: false
}
</script>
inheritAttrs: false
隐藏了根元素上的属性;
v-bind="$attrs"
可将属性绑定到非根元素上。