-
EventBus實例:
var EventBus = new Vue()
會創建一個名為EventBus的Vue實例,并將其存儲在變量EventBus中。Vue.prototype.$bus = new Vue()
則直接在Vue的原型上創建一個新的Vue實例,并將其賦值給$bus屬性。
-
使用方式:
var EventBus = new Vue()
的方式需要你手動導入EventBus實例到需要使用的組件中。Vue.prototype.$bus = new Vue()
的方式則無需手動導入,因為$bus已經成為Vue原型的一部分,你可以在任何組件中直接使用this.$bus來訪問該實例。
-
作用域和生命周期:
var EventBus = new Vue()
創建的EventBus實例的生命周期由你手動管理,需要在適當的時候進行銷毀。Vue.prototype.$bus = new Vue()
創建的$bus實例則隨著Vue應用的生命周期一起管理,當Vue實例被銷毀時,$bus實例也會被銷毀。
因此,雖然這兩種方式都可以實現全局事件總線的功能,但在使用上有一些細微的差別。Vue.prototype.$bus = new Vue()
更加簡潔和方便,特別適合在Vue項目中實現全局事件總線的需求。
EventBus實例?
創建一個名為EventBus的Vue實例(/utils/event-bus.js)
import Vue from 'vue'
export const EventBus = new Vue()
在A組件中的使用
<button @click="sendMsg">按鈕</button>
?// 導入EventBus
import { EventBus } from '@/utils/event-bus.js'
sendMsg() {
// 發送名為'sendMsg'的事件,可以攜帶額外的數據
? ?EventBus.$emit('sendMsg', 'hello')
}
在B組件中的使用
?// 導入EventBus
import { EventBus } from '@/utils/event-bus.js'
created() {
// 監聽名為'sendMsg'的事件
EventBus.$on('sendMsg', (msg) => {
// 處理接收到的事件數據
??????this.msg = msg
})
},
beforeDestroy() {
// 在組件銷毀前取消事件監聽,以避免內存泄漏
????EventBus.$off('sendMsg')
}
$bus實例
var EventBus = new Vue();
這一行代碼創建了一個名為 EventBus 的新的 Vue 實例。這個實例將作為我們的事件總線,用于在 Vue 組件之間進行事件通信。
Object.defineProperties(Vue.prototype, { $bus: { get: function () { return EventBus } } })
這段代碼使用 Object.defineProperties 方法將 $bus 屬性添加到 Vue 的原型上。
定義了 $bus 屬性的 get 方法,當我們在組件中使用 this.$bus 訪問時,實際上是在獲取 EventBus 這個 Vue 實例。
通過在 main.js
中執行這段代碼,我們就可以在整個 Vue 應用中使用 this.$bus
來訪問事件總線實例,方便地實現組件之間的事件通信。
$bus實例(簡潔版)
在 main.js 中添加 $bus:
在 Vue 應用的入口文件 main.js 中添加以下代碼:
import Vue from 'vue';
// 創建一個全局的事件總線并掛載到 Vue 原型上
Vue.prototype.$bus = new Vue();
發送事件:
在任何組件中,可以使用 this.$bus.$emit
發送事件。例如:
export default {
? methods: {
? ? handleClick() {
// 發送名為 'custom-event' 的事件,可以攜帶額外的數據
? ? ? this.$bus.$emit('custom-event', eventData);
? ? }
? }
};
監聽事件:
在需要監聽事件的組件中,使用 this.$bus.$on
方法監聽事件。例如:
export default {
? created() {
// 監聽名為 'custom-event' 的事件
? ? this.$bus.$on('custom-event', this.handleCustomEvent);
? },
? methods: {
? ? handleCustomEvent(data) {
// 處理接收到的事件數據
? ? ? console.log('Received custom event:', data);
? ? }
? },
? beforeDestroy() {
// 在組件銷毀前取消事件監聽,以避免內存泄漏
? ? this.$bus.$off('custom-event', this.handleCustomEvent);
? }
};
?