[Vue] Event Bus 是什麼? 怎麼用?
在 Vue 的組件之間,常見的父子組件溝通方式為 props、emit,但如果是兄弟姊妹組件(如下圖 B 組件和 C 組件)、跨組件之間的溝通,為了避免繁複的 props emit,就可以使用 Event Bus
或是 Vuex
來做。Event Bus
像是一個全域的事件,可以給各組件共用,適用沒有太複雜的專案和事件,如警示視窗,之後會介紹的 Vuex 則適合管理較複雜的全站共用狀態,如登入資訊、購物車…等。
看到有人說 props 和 emit 的記憶口訣是
props in emit out
,常常會搞反的人(我本人)
可以試著這樣記憶看看
要在專案中使用 eventBus 其實就是在 Vue 裡面再註冊一個 Vue 實例,eventBus 主要會使用到 Vue 實例中的四種方法:
$on
:註冊監聽
$once
:只監聽一次
$off
:取消監聽
$emit
:送出事件
建議在頁面 created 的時候就註冊監聽,並在組件銷毀前取消監聽。
範例中我們嘗試製作一個 alert.vue 組件,作為一個全域的警示通知,不管在哪個組件中都可以把這個 alert 事件呼叫出來。
Usage
定義一個新的 Vue 實例
/main.js
Vue.prototype.$bus = new Vue();
建立 bus,監聽事件
/alert.vue
注入
/App.vue
發出事件
/HelloWorld.vue
這樣簡易的全域 eventBus 就完成了。
off
和 once
的使用方法也雷同:
/alert.vue
/HelloWorld.vue
result:
這次的 Event Bus 分享就到這邊,歡迎交流指教 🙋 🙋♂️