vue总线bus的使用和移除注意事项
本文目录
- vue总线bus的使用和移除注意事项
- 初始化并封装
- 发送事件
- 接收事件
- 移除事件监听
- 实际使用
- 正确测试效果
- 错误测试效果
初始化并封装
在main.js
中对bus进行初始化, Bus是一个不具备 DOM 的组件,它具有的仅仅只是它实例方法
Vue.prototype.$bus = new Vue({methods: {emit(event, ...args) {this.$emit(event, ...args);},on(event, callback) {this.$on(event, callback);},off(event, callback) {this.$off(event, callback);}}
});
主要是用on
代替$on
,也可以使用简化的初始化,如下,组件中也带$
即可
Vue.prototype.$bus = new Vue();
组件中可以使用this.$bus
可以查看bus的实例
console.log(this.$bus);
发送事件
两个参数,前一个是事件标识,后一个是发送的内容
this.$bus.emit("radioChange", "test");
接收事件
- 方式一(推荐)
this.$bus.on('radioChange', this.Aaa);Aaa(ii){console.log("radioChange", ii) }
- 方式二(不推荐)
this.$bus.on('radioChange', res => {console.log("radioChange", res) })
移除事件监听
如果不移除,每次进入组件都会新建一个bus监听,导致不断重复
在组件的beforeDestroy
阶段执行
-
方式一:只移除本组件的bus监听
beforeDestroy() {this.$bus.off("radioChange", this.Aaa); },
尽管组件 A 和组件 B 的事件处理器名称可能相同,但它们是不同的函数实例。这是因为在每个组件中,这些方法都是组件实例的成员。因此,当一个组件在销毁时调用
off
,它不会影响其他组件的事件监听器。实际上,每个组件都有自己独立的作用域,
this.Aaa()
在组件 A 和组件 B 的上下文中都是指向组件自己的方法。因此,在组件销毁时使用this.$bus.off('radioChange', this.Aaa)
只会移除当前组件的监听器,不会影响其他组件的监听器。如果接收事件使用方式二,是无法使用此方法进行移除的
-
方式二
会移除所有事件标识为
radioChange
的bus
事件监听this.$bus.off("radioChange");
如果要使用这种方式,需要为每个组件都制定名称不同的事件标识
要避免这种情况,需要为每个组件提供唯一的事件处理函数(发送和接收均使用方式一) -
方式三
移除全部监听,慎用
this.$bus.off();
实际使用
发送组件
<template><div class="page-all"><el-button @click="sendBus">sendBus</el-button><el-button @click="showA = !showA">Turn showA</el-button><el-row style="height: 300px;"><el-col :span="12" v-if="showA"><Ar></Ar></el-col><el-col :span="12"><Br></Br></el-col></el-row></div>
</template><script>
export default {data() {return {showA: true,}},methods: {sendBus(){// console.log(this.$bus);console.log("send");this.$bus.emit("radioChange", "test");},},mounted() {},
}
</script><style scoped></style>
<style></style>
组件A
<template>...
</template><script>
export default {data() {return {}},components: {},methods: {Aaa(ii){console.log("radioChange", ii)}},mounted() {this.$bus.on('radioChange', this.Aaa);},beforeDestroy(){this.$bus.off("radioChange", this.Aaa);},
}
</script>
组件B
<template>...
</template><script>
export default {...methods: {Aaa(ii){console.log("radioChange", ii)}},mounted() {this.$bus.on('radioChange', this.Aaa);},beforeDestroy() {this.$bus.off("radioChange", this.Aaa);},
}
</script>
...
正确测试效果
- 先发送radioChange
- 销毁A组件,发送radioChange,只有B组件能接收
- 生成A组件,发送radioChange,A和B都能收到
错误测试效果
如果A组件没有在销毁前移除事件监听,则经过多次组件的销毁和生成之后,会有多个重复的事件监听,可能造成内存泄漏