一、使用方法
import Vue from "vue";
const EventBus = new Vue();
export default EventBus;
<template>
<div>{{ message }}</div>
</template>
<script>
import eventBus from './event-bus'
export default {
data() {
return {
message: '我是容器A的内容'
}
},
mounted() {
eventBus.$on("sendMessage", (msg) => {
this.message = msg;
})
},
destroyed() {
eventBus.$off("sendMessage")
}
}
</script>
<template>
<button @click="sendToComponentA">点击</button>
</template>
<script>
import eventBus from './event-bus'
export default {
methods: {
sendToComponentA() {
eventBus.$emit("sendMessage", "我来找容器A通信了")
}
}
}
</script>
二、手写实现 EventBus 原理
class EventBus {
constructor() {
this.callbacks = {}
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
console.log('on callback', this.callbacks)
}
$emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach(cb => cb(args));
}
console.log('emit callback', this.callbacks);
}
$off(name) {
if (this.callbacks[name]) delete this.callbacks[name];
console.log('off callback', this.callbacks)
}
}
export default new EventBus();