vue bus实现原理
Vue Event Bus 实现原理
Vue Event Bus 是一种基于 Vue 实例的事件发布/订阅模式,用于组件间通信。其核心原理是利用 Vue 实例的 $emit、$on 和 $off 方法。
核心机制
Vue 实例内部维护了一个事件中心(Event Hub),通过 _events 私有属性存储事件监听器。当调用 $on 时,会将回调函数注册到对应事件名的数组中;$emit 触发时遍历执行该事件的所有回调;$off 用于移除监听。

实现代码示例
创建一个全局 Event Bus:
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
组件中使用方式:

// 发送事件
EventBus.$emit('event-name', payload)
// 接收事件
EventBus.$on('event-name', (payload) => {
console.log(payload)
})
// 移除监听
EventBus.$off('event-name')
底层实现分析
Vue 源码中相关方法的核心逻辑:
// $on 实现
Vue.prototype.$on = function (event, fn) {
const vm = this
;(vm._events[event] || (vm._events[event] = [])).push(fn)
return vm
}
// $emit 实现
Vue.prototype.$emit = function (event) {
const vm = this
let cbs = vm._events[event]
if (cbs) {
const args = Array.from(arguments).slice(1)
for (let i = 0; i < cbs.length; i++) {
cbs[i].apply(vm, args)
}
}
return vm
}
注意事项
Event Bus 适合中小型项目,但在大型项目中可能导致事件难以追踪。需注意及时移除监听避免内存泄漏,通常在组件 beforeDestroy 钩子中调用 $off。
Vue 3 中因移除 $on 等 API,推荐使用 mitt 等第三方库实现类似功能。






