作用:实现组件间平行通信
优点:
- 解决了多层组件之间繁琐的事件传播。
- 使用原理十分简单,代码量少。
缺点:
- 使用成本低,难以维护;
- 可能存在重复触发的情况,要求及时销毁
建议:用 vuex 代替事件总线
具体使用:
- 新建bus.js文件
import Vue from 'vue';
const bus = new Vue({
data() {
return {
count: 0,
onceCount: 1
}
},
created() {
this.$on("msg", () => {
this.count++
})
// 只发生一次
this.$once("onceMsg", data => {
this.onceCount += data
})
},
beforeDestroy() {
this.$off("msg");
this.$off("onceMsg");
}
})
export default bus;
- main.js中引入
import bus from "./bus";
Vue.prototype.$bus = bus;
- A组件
<template>
<div>
<button @click="sendMsg">发送一条消息</button>
<button @click="sendOnce">只发送一次</button>
</div>
</template>
<script>
export default {
methods: {
sendMsg() {
this.$bus.$emit("msg")
},
sendOnce() {
this.$bus.$emit("onceMsg", 4)
}
}
};
</script>
- B组件
<template>
<div>
<p>接收到的消息是:{{ count }}</p>
<p>一次性消费:{{ onceCount }}</p>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$bus.count;
},
onceCount() {
return this.$bus.onceCount;
}
},
}
</script>