Vue事件总线
下面,我们来系统的梳理关于 Vue 事件总线模式 的基本知识点
一、事件总线核心概念
1.1 什么是事件总线?
事件总线是一种发布-订阅模式的实现,用于在Vue组件之间进行通信,特别适合处理非父子关系的组件间通信。它充当一个中央事件处理中心,组件可以触发事件或监听事件,而不需要直接引用彼此。
1.2 事件总线原理
1.3 适用场景
- 非父子组件通信:兄弟组件、跨层级组件
- 全局事件通知:用户登录/登出、全局错误处理
- 解耦组件:避免组件间直接依赖
- 简单状态变更:不需要复杂状态管理的场景
二、事件总线实现方案
2.1 Vue 2 实现
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()// 或全局挂载
Vue.prototype.$eventBus = new Vue()
2.2 Vue 3 实现(推荐)
// event-bus.js
import mitt from 'mitt'// 创建事件总线实例
const emitter = mitt()// 添加高级功能
export const EventBus = {emit: emitter.emit,on: emitter.on,off: emitter.off,// 添加一次性事件监听once(event, handler) {const wrapper = (payload) => {handler(payload)this.off(event, wrapper)}this.on(event, wrapper)},// 添加带命名空间的事件namespacedEmit(namespace, event, payload) {this.emit(`${namespace}:${event}`, payload)},namespacedOn(namespace, event, handler) {this.on(`${namespace}:${event}