今天在項目的一個元件需要向兄弟元件傳資料,是以想到了使用eventBus。
首先,我先建立了一個eventBus.js,代碼如下:
import Vue from 'vue'
const eventBus = new Vue()
export default eventBus
然後在需要往外傳值的元件中引用eventBus.js:
import eventBus from '@/assets/js/eventBus'
在方法中使用$emit往外傳值:
eventBus.$emit('dataUpdate',data)
在需要接受值的兄弟元件中再次引用eventBus.js:
import eventBus from '@/assets/js/eventBus'
在created()周期函數裡使用$on來接受其他元件傳來的值:
created(){
eventBus.$on('dataUpdate', item => {
this.name = item
console.log(this.name)
})
}
然後我就遇到了一個奇怪的事情,console.log可以列印出this.name的值,但是頁面上的name沒有任何變化,還是data()函數裡的初始值。
通過查詢資料得知原來 vue路由切換時,會先加載新的元件,等新的元件渲染好但是還沒有挂載前,銷毀舊的元件,之後挂載新元件,如下圖所示:
新元件beforeCreate
↓
新元件created
↓
新元件beforeMount
↓
舊元件beforeDestroy
↓
舊元件destroyed
↓
新元件mounted
注意,在
$emit
時,必須已經
$on
,否則将無法監聽到事件。
是以正确的寫法應該是在需要接收值的元件的
created
生命周期函數裡寫
$on
,在需要往外傳值的元件的
destroyed
生命周期函數函數裡寫:
destroyed(){
eventBus.$emit('dataUpdate',data)
}
這樣寫,在舊元件銷毀的時候新的元件拿到舊元件傳來的值,然後在挂載的時候更新頁面裡的資料。