如果想要使用事件总线进行组件之间的传值,首先我们需要将$eventBus挂载到vue实例上面
然后在A页面使用this.$eventBus.$emit("命名", 值);触发事件总线
B页面实现监控this.$eventBus.$on("命名", (event) => {}(需要注意,此处命名需要和this.$eventBus.$emit之中的命名保持一致)
需要注意一点就是,事件总线用完需要移除,一般会在组件销毁生命周期内移除,避免多次触发
下面是代码:
//main.js
import Vue from 'vue'
Vue.prototype.$eventBus = new Vue()//挂载到vue实例上全局定义
//bortherOne.vue
<template>
<div>
<button @click="btn">点击传值</button>
bortherOne
</div>
</template>
<script>
export default {
name: "bortherOne",
data() {
return {
bortherOneValue: "我是bortherOne",
};
},
mounted() {},
methods: {
btn() {
this.$eventBus.$emit("deliverValue", this.bortherOneValue);//发起
},
},
};
</script>
//bortherTwo.vue
<template>
<div>
<p>bortherTwo{{ bortherTwoValue }}</p>
</div>
</template>
<script>
export default {
name: "bortherTwo",
data() {
return {
bortherTwoValue: "我是bortherTwo,我负责接收值",
};
},
mounted() {
this.$eventBus.$on("deliverValue", (event) => {//监听接收传过来的值
this.bortherTwoValue = event;
console.log(this.bortherTwoValue);
console.log(event, "event");
this.getData(event);
});
},
methods: {
getData(event) {
console.log(event, "在getdata里面打印接收到的值");
},
},
beforeDestory() {
this.$eventBus.$off("deliverValue");//避免多次触发
},
};
</script>
除了上面这种初始时候在main.js之中直接将eventBus挂载到vue实例上面的方法,我们还可以是使用封装js文件的方法实现事件总线传值,代码如下:
//bus.js
import Vue from 'vue';
// 使用 Event Bus
const bus = new Vue();
export default bus;
//使用的时候
import bus from '../utils/bus.js
bus.$emit("collapse", this.collapse);//触发
bus.$on("collapse", data => {})//监听
bus.$off("collapse")//移除
封装js文件的方法,多了一步导入需要用到的文件,其他触发,移除,监听基本一致这里不过多赘述