1. eventbus 的简介
eventbus又称为事件总线, 在vue中能够应用eventbus来作为沟通桥梁的概念, 是所有组件所共有的事件核心.能够向该核心注册发送事件或接管事件.所以组件都能够高低平行地告诉其余组件
2. 如何应用eventbus
(1) 初始化
首先须要创立事件总线并将其导出,以便其余模块能够应用或者监听它,有两种形式解决
第一种,新建一个js文件,比方event-bus.js
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
实际上eventbus是一个不具备dom的组件
另外一种形式,能够间接在我的项目中的main.js初始化EventBus:
// main.js
Vue.prototype.$EventBus = new Vue()
// 留神这种形式初始化的EventBus是一个全局事件总线,
(2) 发送事件
假如有两个vue页面须要通信, A页面在按钮下面绑定了点击事件,发送一则音讯,告诉B页面
// A 页面
<template>
<button @click="sendMsg()">-</button>
</template>
<script> import { EventBus } from "../event-bus.js";
export default {
methods: {
sendMsg() {
EventBus.$emit("aMsg", '来自A页面的音讯');
}
}
}; </script>
接下来在B页面接管音讯
(3) 接管事件
<!-- IncrementCount.vue -->
<template>
<p>{{msg}}</p>
</template>
<script> import {
EventBus
} from "../event-bus.js";
export default {
data(){
return {
msg: ''
}
},
mounted() {
EventBus.$on("aMsg", (msg) => {
// A发送来的音讯
this.msg = msg;
});
}
}; </script>
后面提过,如果应用不善,eventBus会是一个劫难, vue是单页面利用,如果你再某一个页面刷新之后,与之相干的eventbus将会被移除, 这样会导致业务走不上来. 还有就是如果业务有重复操作的页面, eventBus在监听的时候就会触发很屡次, 也是一个十分大的隐患. 这时候咱们须要好好解决eventbus在我的项目中的关系, 通常是在vue页面销毁的时候,共事移除eventbus事件监听
移除事件监听
import {
eventBus
} from './event-bus.js'
EventBus.$off('aMsg', {})
你可是要EventBus.$off(‘eqwe’)移除利用内所有对此某个事件的监听, 或者间接调用EventBus.$off() 来移除所有事件频道.不增加任何参数~~~~
3. 全局eventbus
它的工作原理是公布/订阅办法, 通常称为pub/sub
创立全局EventBus
// 1. 创立bus.js文件 **src/service/bus.js**
const install = (Vue) => {
const Bus = new Vue({
methods: {
on (event, ...args) {
this.$on(event, ...args);
},
emit (event, callback) {
this.$emit(event, callback);
},
off (event, callback) {
this.$off(event, callback);
}
}
})
Vue.prototype.$bus = Bus;
}
export default install;
// **maix.js文件中引入**
import Bus from "@/service/bus";
Vue.use(Bus);
// **组件中应用**
this.$bus.on('Config_forms',(data)=>{ }) //绑定事件
this.$bus.emit('Config_forms',data) //触发该办法 this.$bus.off('Config_forms') //解绑事件
发表回复