实现Vue事件总线
事件总线的作用
事件总线(Event Bus)是一种跨组件通信机制,适用于非父子组件或兄弟组件之间的数据传递。Vue 2 中常用 new Vue() 实例作为事件总线,Vue 3 推荐使用第三方库(如 mitt)或 provide/inject 替代。
Vue 2 的实现方式
1. 创建事件总线实例
在项目中新建一个文件(如 eventBus.js),导出 Vue 实例:
import Vue from 'vue';
export const eventBus = new Vue();
2. 发送事件
在需要传递数据的组件中,通过 $emit 触发事件:
import { eventBus } from './eventBus.js';
eventBus.$emit('custom-event', data);
3. 监听事件
在接收数据的组件中,通过 $on 监听事件:

import { eventBus } from './eventBus.js';
eventBus.$on('custom-event', (data) => {
console.log('Received:', data);
});
4. 移除监听
为避免内存泄漏,在组件销毁时移除监听:
beforeDestroy() {
eventBus.$off('custom-event');
}
Vue 3 的替代方案
Vue 3 移除了 $on、$off 等实例方法,推荐以下方式:
1. 使用 mitt 库
安装 mitt:

npm install mitt
创建事件总线:
import mitt from 'mitt';
export const eventBus = mitt();
发送与监听事件:
// 发送事件
eventBus.emit('custom-event', data);
// 监听事件
eventBus.on('custom-event', (data) => {
console.log('Received:', data);
});
// 移除监听
eventBus.off('custom-event');
2. 使用 provide/inject
适用于依赖注入的场景,但需注意响应性:
// 祖先组件提供数据
import { provide, ref } from 'vue';
const sharedData = ref(null);
provide('sharedData', sharedData);
// 后代组件接收数据
import { inject } from 'vue';
const receivedData = inject('sharedData');
注意事项
- 命名冲突:事件名建议使用唯一标识(如模块前缀)。
- 内存泄漏:组件销毁时需清理监听器(Vue 2 的
$off或mitt的off)。 - 响应式数据:直接传递响应式对象可能导致意外更新,建议传递纯数据或使用
toRefs。
通过以上方法,可以灵活实现跨组件通信,根据项目需求选择适合的方案。






