vue中组件通信父??子通过props ,子??父通过$emit ,那么父??孙,孙??父呢?
通常使用的方法是通过vuex 。如果仅仅是传递数据,而不做其他处理,使用 vuex 处理有点大材小用。  所以就有了 $attrs / $listeners ,通常配合inheritAttrs 一起使用。(注意:是2.4新增的)
📙inheritAttrs
inheritAttrs的讲解参考官网,如下图所示: 
📙$attrs / $listeners
📒$attrs
📒$listeners
- 官网讲解
 - 🌰例子
- 父组件(component_parent.vue)
<template>
<div>
<child :parent="parentString" :info="info" @updateInfo="updateInfo"></child>
</div>
</template>
<script>
import child from "./component_child"
export default {
name: '',
components: { child },
data() {
return {
parentString: "这是父组件",
info: {
name: "张三",
address: "陕西省"
}
}
},
methods: {
updateInfo() {
console.log('更新父组件');
}
},
};
</script>
- 子组件(component_child.vue)
<template>
<div>
<div>{{parent}}</div>
<div>子组件:{{$attrs}}</div>
<grandson v-bind="$attrs" :message="message" @childInfo="childInfo"></grandson>
</div>
</template>
<script>
import grandson from './component_grandson.vue'
export default {
name: '',
components: { grandson },
props: [parent],
data() {
return {
message: "这是子组件的传值"
};
},
mounted() {
console.log('child-listeners', this.$listeners);
},
methods: {
childInfo() {
console.log('更新子组件');
}
},
};
</script>
- component_grandson.vue
<template>
<div>孙子组件:{{$attrs}}</div>
</template>
<script>
export default {
name: '',
data() {
return {
};
},
mounted() {
console.log('grandson-listeners', this.$listeners);
this.$emit('updateInfo')
},
</script>

以上就是$attrs 和$listeners 的使用,有问题欢迎随时指出!🏄🏄🏄
|