eventbus vue实现
EventBus 在 Vue 中的实现
EventBus 是一种基于发布-订阅模式的通信机制,适合在 Vue 组件间实现跨层级通信。以下是具体实现方法:
创建 EventBus 实例
在项目中新建一个文件(如 event-bus.js),通过 Vue 实例创建 EventBus:
import Vue from 'vue';
export const EventBus = new Vue();
发送事件(发布)
在需要发送事件的组件中,通过 $emit 触发自定义事件:
import { EventBus } from './event-bus.js';
// 发送事件,可携带数据
EventBus.$emit('eventName', payload);
eventName:自定义事件名称payload:可选参数,传递的数据
接收事件(订阅)
在需要接收事件的组件中,通过 $on 监听事件:

import { EventBus } from './event-bus.js';
EventBus.$on('eventName', (payload) => {
console.log('接收到数据:', payload);
});
移除事件监听
为避免内存泄漏,在组件销毁时(如 beforeDestroy 钩子)移除监听:
EventBus.$off('eventName');
若要移除所有监听,可不传参数:

EventBus.$off();
一次性监听
若只需监听一次事件,使用 $once:
EventBus.$once('eventName', (payload) => {
console.log('仅触发一次:', payload);
});
注意事项
- 命名冲突:建议使用统一的命名规范(如模块名前缀)避免事件名重复。
- 内存管理:务必在组件销毁时清理监听,防止重复订阅。
- 替代方案:复杂场景建议使用 Vuex 状态管理。
完整示例
组件 A(发送事件)
<template>
<button @click="sendMessage">发送消息</button>
</template>
<script>
import { EventBus } from './event-bus.js';
export default {
methods: {
sendMessage() {
EventBus.$emit('message', { text: 'Hello from A' });
}
}
};
</script>
组件 B(接收事件)
<script>
import { EventBus } from './event-bus.js';
export default {
created() {
EventBus.$on('message', (payload) => {
console.log('B组件收到:', payload.text);
});
},
beforeDestroy() {
EventBus.$off('message');
}
};
</script>






