ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[链接](https://segmentfault.com/a/1190000019208626) ## 方法四、`$attrs`/`$listeners` #### 1.简介 多级组件嵌套需要传递数据时,通常使用的方法是通过vuex。但如果仅仅是传递数据,而不做中间处理,使用 vuex 处理,未免有点大材小用。为此Vue2.4 版本提供了另一种方法----`$attrs`/`$listeners` * `$attrs`:包含了父作用域中不被 prop 所识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件。通常配合 interitAttrs 选项一起使用。 * `$listeners`:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件 接下来我们看个跨级通信的例子: 接下来我们看个跨级通信的例子: ~~~ // index.vue <template> <div> <h2>浪里行舟</h2> <child-com1 :foo="foo" :boo="boo" :coo="coo" :doo="doo" title="前端工匠" ></child-com1> </div> </template> <script> const childCom1 = () => import("./childCom1.vue"); export default { components: { childCom1 }, data() { return { foo: "Javascript", boo: "Html", coo: "CSS", doo: "Vue" }; } }; </script> ~~~ ~~~ // childCom1.vue <template class="border"> <div> <p>foo: {{ foo }}</p> <p>childCom1的$attrs: {{ $attrs }}</p> <child-com2 v-bind="$attrs"></child-com2> </div> </template> <script> const childCom2 = () => import("./childCom2.vue"); export default { components: { childCom2 }, inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性 props: { foo: String // foo作为props属性绑定 }, created() { console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" } } }; </script> ~~~ ~~~ // childCom2.vue <template> <div class="border"> <p>boo: {{ boo }}</p> <p>childCom2: {{ $attrs }}</p> <child-com3 v-bind="$attrs"></child-com3> </div> </template> <script> const childCom3 = () => import("./childCom3.vue"); export default { components: { childCom3 }, inheritAttrs: false, props: { boo: String }, created() { console.log(this.$attrs); // {"coo": "CSS", "doo": "Vue", "title": "前端工匠" } } }; </script> ~~~ ~~~ // childCom3.vue <template> <div class="border"> <p>childCom3: {{ $attrs }}</p> </div> </template> <script> export default { props: { coo: String, title: String } }; </script> ~~~ ![](https://img.kancloud.cn/d5/df/d5df9f69b7fea3bf26e85f90f3852bb6_569x227.png) 如上图所示`$attrs`表示没有继承数据的对象,格式为{属性名:属性值}。Vue2.4提供了`$attrs`,`$listeners`来传递数据与事件,跨级组件之间的通讯变得更简单。 简单来说:`$attrs`与`$listeners`是两个对象,`$attrs`里存放的是父组件中绑定的非 Props 属性,`$listeners`里存放的是父组件中绑定的非原生事件。 ## 方法五、provide/inject