Vue事件总线(EventBus)简单使用

418 阅读1分钟

写组件的时候需要用到组件创造,props传值难以满足需要,需要用到事件总线( EventBus)来处理,下面总结个人对EventBus的使用理解

一、初始化

import Vue from "vue";

data() {
    return {
      eventBus: new Vue(),
    };
},

二、发送事件

this.eventBus.$emit("update:selected", this.selected);

三、接收事件

inject: ["eventBus"],
this.eventBus.$on("update:selected",(item)=>{
  // console.log(item)
})

移除事件监听者

EventBus.$off('update:selected', {})

也可以讲eventBus全局封装

新创建一个 .js 文件,比如 event-bus.js

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

另外一种方式,可以直接在项目中的 main.js 初始化 EventBus :

// main.js
Vue.prototype.$EventBus = new Vue()

页面中使用EventBus

import { EventBus } from "../event-bus.js";

发送EventBus

EventBus.$emit("update:selected", 'this.selected');

接收EventBus

EventBus.$on("update:selected", 'this.selected');

移除事件监听者

EventBus.$off('aMsg', {})

如果使用不善,EventBus会是一种灾难,到底是什么样的“灾难”了?大家都知道vue是单页应用,如果你在某一个页面刷新了之后,与之相关的EventBus会被移除,这样就导致业务走不下去。还要就是如果业务有反复操作的页面,EventBus在监听的时候就会触发很多次,也是一个非常大的隐患。这时候我们就需要好好处理EventBus在项目中的关系。通常会用到,在vue页面销毁时,同时移除EventBus事件监听。