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);

發(fā)送事件
兩個參數(shù),前一個是事件標識,后一個是發(fā)送的內容
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)
})
移除事件監(jiān)聽
如果不移除,每次進入組件都會新建一個bus監(jiān)聽,導致不斷重復
在組件的beforeDestroy階段執(zhí)行
方式一:只移除本組件的bus監(jiān)聽
beforeDestroy() {
this.$bus.off("radioChange", this.Aaa);
},
盡管組件 A 和組件 B 的事件處理器名稱可能相同,但它們是不同的函數(shù)實例。這是因為在每個組件中,這些方法都是組件實例的成員。因此,當一個組件在銷毀時調用 off,它不會影響其他組件的事件監(jiān)聽器。
實際上,每個組件都有自己獨立的作用域,this.Aaa() 在組件 A 和組件 B 的上下文中都是指向組件自己的方法。因此,在組件銷毀時使用 this.$bus.off('radioChange', this.Aaa) 只會移除當前組件的監(jiān)聽器,不會影響其他組件的監(jiān)聽器。
如果接收事件使用方式二,是無法使用此方法進行移除的
方式二
會移除所有事件標識為radioChange的bus事件監(jiān)聽
this.$bus.off("radioChange");如果要使用這種方式,需要為每個組件都制定名稱不同的事件標識
要避免這種情況,需要為每個組件提供唯一的事件處理函數(shù)(發(fā)送和接收均使用方式一)
方式三
移除全部監(jiān)聽,慎用
this.$bus.off();
實際使用
發(fā)送組件
<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>
...正確測試效果

先發(fā)送radioChange銷毀A組件,發(fā)送radioChange,只有B組件能接收生成A組件,發(fā)送radioChange,A和B都能收到

錯誤測試效果
如果A組件沒有在銷毀前移除事件監(jiān)聽,則經(jīng)過多次組件的銷毀和生成之后,會有多個重復的事件監(jiān)聽,可能造成內存泄漏

到此這篇關于Vue中使用和移除總線Bus的注意事項詳解的文章就介紹到這了,更多相關Vue使用和移除總線Bus內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3如何優(yōu)雅的實現(xiàn)移動端登錄注冊模塊
這篇文章主要給大家介紹了關于vue3如何優(yōu)雅的實現(xiàn)移動端登錄注冊模塊的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
vue3中el-uplod結合ts實現(xiàn)圖片粘貼上傳
本文主要介紹了vue3中el-uplod結合ts實現(xiàn)圖片粘貼上傳,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-07-07

