組件傳值

  • 2022 年 5 月 28 日
  • 筆記

事件匯流排:
就是創建一個事件中心,相當於中轉站,可以用它來傳遞事件和接收事件

1.創建全局空Vue實例:eventBus

import Vue from 'vue';
const eventBus= new Vue()  //創建事件匯流排
export default eventBus;

2.具體頁面使用$emit發布事件 – 傳遞值

import eventBus from '@u/eventBus'
eventBus.$emit('send',『hello』)

3.具體頁面使用$on訂閱事件 – 接收組件值

import eventBus from '@u/eventBus'
eventBus.$on('send', msg => {
	console.log(msg)  //控制台輸出 hello
}

注意:\(on先進行監聽,一旦\)emit發布事件後所有組件都可以\(on監聽到事件。所以傳遞參數的時候一定已經先進行了監聽才能得到參數。比如在父組件中\)emit事件放在mounted鉤子函數中,等待子組件創建並\(on開始監聽事件後再去觸發\)emit發布事件。

4.$off()移除事件監聽

import eventBus from '@u/eventBus'
eventBus.$off('send')  

事件訂閱功能\(on是\)eventBus對象完成的,與組件無關,如果用v-if銷毀子組件的時候,會形成閉包,造成記憶體泄露,所有要在銷毀組件的時候進行取消監聽事件