eventbus vue实现
EventBus 实现原理
EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。
创建 EventBus
在 Vue 项目中创建一个独立的 EventBus 实例:
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
发送事件
在需要发送事件的组件中,通过 $emit 触发事件并传递数据:

// ComponentA.vue
import { EventBus } from './event-bus.js';
EventBus.$emit('event-name', { data: 'some data' });
监听事件
在需要接收事件的组件中,通过 $on 监听事件并处理数据:
// ComponentB.vue
import { EventBus } from './event-bus.js';
EventBus.$on('event-name', (data) => {
console.log('Received data:', data);
});
移除监听
为避免内存泄漏,在组件销毁时移除事件监听:

// ComponentB.vue
beforeDestroy() {
EventBus.$off('event-name');
}
全局 EventBus
若需全局使用,可将 EventBus 挂载到 Vue 原型上:
// main.js
import Vue from 'vue';
import App from './App.vue';
Vue.prototype.$eventBus = new Vue();
new Vue({
render: h => h(App),
}).$mount('#app');
使用时直接通过 this.$eventBus 访问:
// 发送事件
this.$eventBus.$emit('global-event');
// 监听事件
this.$eventBus.$on('global-event', () => {});
注意事项
- 避免过度使用 EventBus,复杂场景建议使用 Vuex。
- 确保及时移除监听,防止内存泄漏。
- 事件命名建议使用常量或统一前缀,避免冲突。
替代方案
对于简单场景,也可直接使用 Vue 内置的 $emit 和 $on:
// 父组件监听子组件事件
<child-component @custom-event="handleEvent" />
// 子组件触发事件
this.$emit('custom-event', data);






