定义
全局定义,可以将eventBus绑定到vue实例的原型上,也可以直接绑定到window对象上。
//main.js(可以是任意JS写)
//方式一
Vue.prototype.$EventBus = new Vue();
// 在mian中,方式一可以这么写
new Vue({
router,
render: h => h(App),
beforeCreated() {
Vue.prototype.$EventBus = this
}
}).$mount('#app')
//方式二
window.eventBus = new Vue();
触发事件
//使用方式一定义时
this.$EventBus.$emit('eventName', param1,param2,...)
//使用方式二定义时
EventBus.$emit('eventName', param1,param2,...)
监听事件
//使用方式一定义时
this.$EventBus.$on('eventName', (param1,param2,...)=>{
//需要执行的代码
})
//使用方式二定义时
EventBus.$on('eventName', (param1,param2,...)=>{
//需要执行的代码
})
移除监听事件
为了避免在监听时,事件被反复触发,通常需要在页面销毁时移除事件监听。或者在开发过程中,由于热更新,事件可能会被多次绑定监听,这时也需要移除事件监听。
//使用方式一定义时
this.$EventBus.$off('eventName');
//使用方式二定义时
EventBus.$off('eventName');