🌟 前言
歡迎來到我的技術小宇宙!🌌 這里不僅是我記錄技術點滴的后花園,也是我分享學習心得和項目經驗的樂園。📚 無論你是技術小白還是資深大牛,這里總有一些內容能觸動你的好奇心。🔍
🤖 洛可可白:個人主頁
🔥 個人專欄:?前端技術 ?后端技術
🏠 個人博客:洛可可白博客
🐱 代碼獲取:bestwishes0203
📷 封面壁紙:洛可可白wallpaper

這里寫自定義目錄標題
- Vue 全局事件總線:Vue 2 vs Vue 3 實現
- 引言
- Vue 2 全局事件總線
- 實現步驟
- Vue 3 全局事件總線
- 實現步驟
- 比較與結論
- Vue 2 事件總線
- Vue 3 事件總線
Vue 全局事件總線:Vue 2 vs Vue 3 實現
引言
在構建大型Vue應用時,跨組件通信是一個常見需求。Vue提供了多種通信方式,包括父子組件傳參、兄弟組件通信、Vuex狀態管理等。然而,對于簡單的跨組件通信,全局事件總線(Event Bus)提供了一種輕量級的解決方案。本文將比較在Vue 2和Vue 3中實現全局事件總線的方法,并探討各自的優缺點。
Vue 2 全局事件總線
在Vue 2中,全局事件總線通常通過創建一個新的Vue實例來實現,這個實例作為中央樞紐供所有組件使用。
實現步驟
- 創建事件總線
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
- 在組件中使用事件總線
<template><button @click="emitEvent">發射事件</button>
</template><script>
import { EventBus } from './event-bus.js';export default {methods: {emitEvent() {EventBus.$emit('my-event', '這是來自組件A的消息');}}
}
</script>
<template><div><h2>事件消息:{{ message }}</h2></div>
</template><script>
import { EventBus } from './event-bus.js';export default {data() {return {message: ''};},created() {EventBus.$on('my-event', this.handleEvent);},methods: {handleEvent(msg) {this.message = msg;}},beforeDestroy() {EventBus.$off('my-event', this.handleEvent);}
}
</script>
Vue 3 全局事件總線
Vue 3引入了組合式API,提供了更多靈活性。我們可以利用這些新特性來實現全局事件總線。
實現步驟
- 創建事件總線
// event-bus.js
import { reactive, readonly } from 'vue';const state = reactive(new Map());function emit(event, payload) {(state.get(event) || []).forEach((callback) => callback(payload));
}function on(event, callback) {if (!state.has(event)) {state.set(event, []);}state.get(event).push(callback);return () => off(event, callback);
}function off(event, callback) {const callbacks = state.get(event);if (callbacks) {callbacks.splice(callbacks.indexOf(callback), 1);}
}export const EventBus = {emit,on,off,readonly: readonly(state),
};
- 在組件中使用事件總線
<template><button @click="emitEvent">發射事件</button>
</template><script setup>
import { EventBus } from './event-bus.js';const emitEvent = () => {EventBus.emit('my-event', '這是來自組件A的消息');
};
</script>
<template><div><h2>事件消息:{{ message }}</h2></div>
</template><script setup>
import { ref, onUnmounted } from 'vue';
import { EventBus } from './event-bus.js';const message = ref('');const listener = (msg) => {message.value = msg;
};EventBus.on('my-event', listener);onUnmounted(() => {EventBus.off('my-event', listener);
});
</script>
比較與結論
Vue 2 事件總線
- 優點:簡單易用,不需要額外的庫或工具。
- 缺點:隨著應用規模的增長,事件總線可能會變得難以維護,且不易于跟蹤事件的來源和去向。
Vue 3 事件總線
- 優點:利用組合式API,代碼更加模塊化,易于維護。響應式的狀態管理使得事件監聽和發射更加靈活。
- 缺點:需要對組合式API有一定的了解,對于初學者來說可能有一定的學習曲線。
如果對你有幫助,點贊👍、收藏💖、關注🔔是我更新的動力!👋🌟🚀