EventBus
# EventBus
EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件。EventBus主要是用到发布者-订阅者的设计模式,所以代码里需要有一个地方注册事件,有另外一个或多个地方订阅事件。
vue组件之间的通信,常见的有父传子,子传父,或者兄弟组件间互传,涉及到跨页面时需要用到vuex或者缓存的方式传值。一般来说用vuex做状态管理是项目的首选,但有一些小型而且快消的项目,对后期维护要求不高的,也可以考虑用EventBus作为通信方式。EventBus的有点在于灵活,去中心化,代码量少。
# 代码实现
// 1.
// units/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;
// main.js
import Vue from "vue";
import Bus from "./utils/bus";
Vue.use(Bus);
// 2.
// main.js
// Vue.prototype.$EventBus = new Vue()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// view/A.vue
created() {
//事件订阅
this.$bus.on("addProduct", res => {
this.product = res;
});
},
beforeDestroy() {
//销毁监听事件
this.$bus.off("addProduct");
}
// view/B.vue
addProduct(row) {
//事件发布
this.$bus.emit("addProduct", row);
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
编辑 (opens new window)
上次更新: 2023/04/01, 15:26:22