在 Vue 2 中,全局事件总线(EventBus)是一种常用的非父子组件通信方案。其核心原理是利用 Vue 实例本身具备的事件系统(on, emit, $off),创建一个独立的、不包含 DOM 的 Vue 实例作为中央事件中心。
Vue 2 的全局事件总线示例,涵盖初始化、绑定、分发和解绑四个步骤。
指定事件总线对象 (初始化)
通常有两种方式创建全局事件总线。推荐在 main.js 中将其挂载到 Vue 原型上,这样所有组件实例都可以通过 this.$bus 访问。
文件:main.js
javascript
import Vue from 'vue'
import App from './App.vue'
// 1. 创建一个空的 Vue 实例作为事件总线
const bus = new Vue()
// 2. 将其挂载到 Vue 原型上,使所有组件可通过 this.$bus 访问
Vue.prototype.$bus = bus
new Vue({
render: h => h(App),
}).$mount('app')
绑定事件监听 (on / once)
在需要接收数据的组件中(例如组件 B),通常在生命周期钩子 created 或 mounted 中绑定事件监听。
ComponentB.vue (接收方)
javascript
<template>
<div>
<p>接收到的消息: {{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
created() {
// 方法一:使用 $on 持续监听
// 第一个参数是事件名,第二个参数是回调函数
this.$bus.$on('update-message', (data) => {
console.log('ComponentB 收到数据:', data)
this.message = data
})
// 方法二:使用 $once 只监听一次
// 适用于只需要处理第一次触发的场景
/*
this.$bus.$once('init-data', (data) => {
console.log('只执行一次:', data)
})
*/
}
}
</script>
分发事件 ($emit)
在需要发送数据的组件中(例如组件 A),通过 $emit 触发事件并传递数据。
ComponentA.vue (发送方)
javascript
<template>
<div>
<button @click="sendMessage">发送消息给 ComponentB</button>
</div>
</template>
<script>
export default {
methods: {
sendMessage() {
// 触发名为 'update-message' 的事件,并传递数据
this.$bus.$emit('update-message', 'Hello from Component A!')
}
}
}
</script>
解绑事件监听 ($off)
为了避免内存泄漏和重复执行回调,必须在组件销毁前解绑事件监听。通常在 beforeDestroy (Vue 2) 生命周期钩子中进行。
ComponentB.vue (接收方 - 补充解绑逻辑)
javascript
<script>
export default {
data() {
return {
message: ''
}
},
methods: {
// 建议将回调函数定义为方法,以便在 $off 中引用相同的函数地址
handleUpdateMessage(data) {
this.message = data
}
},
created() {
// 绑定事件时使用方法引用
this.$bus.$on('update-message', this.handleUpdateMessage)
},
beforeDestroy() {
// 解绑事件
// 必须确保事件名和回调函数引用与 $on 时完全一致
this.$bus.$off('update-message', this.handleUpdateMessage)
// 如果想解绑该总线上的所有监听器(慎用):
// this.$bus.$off()
}
}
</script>