共计 1814 个字符,预计需要花费 5 分钟才能阅读完成。
序言:vue 组件通信方式大家都会有所了解,大多涉及到的也都是父子组件通信或者是兄弟组件通信,至于祖孙组件通信大多使用 Vuex 仓库实现。本文将使用一种全新的方式实现组件(无论隔几代)间通信。
1、封装广播方法
//emitter.js
function broadcast(componentName, eventName, params) {
this.$children.forEach(child => {
const name = child.$options.name;
if (name === componentName) {child.$emit.apply(child, [eventName].concat(params));
} else {broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
export default {
methods: {dispatch(componentName, eventName, params) {
let parent = this.$parent || this.$root;
let name = parent.$options.name;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {name = parent.$options.name;}
}
if (parent) {parent.$emit.apply(parent, [eventName].concat(params));
}
},
broadcast(componentName, eventName, params) {broadcast.call(this, componentName, eventName, params);
}
}
};
2、组件通信案例
//Index.vue
<template>
<div>
<component-a>
<component-b></component-b>
</component-a>
</div>
</template>
<script>
import ComponentA from './A';
import ComponentB from './B';
export default {
name: 'list',
components: {
ComponentA,
ComponentB
},
data() {return {}
},
}
</script>
//A.vue
<template>
<div>
<button @click="greetB"> 向组件 B 发送消息 </button>
<slot></slot>
</div>
</template>
<script>
import Emitter from '../../assets/js/emitter.js';
export default {
name: 'componentA',
mixins: [Emitter],
created() {
// 监听子组件 B 传过来的问候
this.$on("sendToA", this.showMessage);
},
methods: {showMessage(text) {window.alert(text);
},
greetB() {
// 向子组件 B 问候
this.broadcast('componentB', 'sendToB', 'Hello B!, i love you');
}
}
}
</script>
//B.vue
<template>
<div>
<button @click="greetA"> 向组件 A 发送消息 </button>
</div>
</template>
<script>
import Emitter from '../../assets/js/emitter.js';
export default {
name: 'componentB',
mixins: [Emitter],
created () {
// 监听父组件 A 传过来的问候
this.$on('sendToB', this.showMessage);
},
methods: {showMessage(text) {window.alert(text);
},
greetA() {
// 向父组件 A 问候
this.dispatch("componentA", "sendToA", "hello A!, i love you too");
}
}
}
</script>
运行结果:
正文完