Vue使用bus總線時,第一次路由跳轉時數據沒成功傳遞的原因以及解決辦法
bus總線是vue中路由跳轉傳遞數據的常用方法,適用於傳遞數據不多的情況,但是在使用的過程中發現,bus總線在第一次路由跳轉的時候總是不能夠成功傳遞需要傳遞的數據。檢查bus的配置以及調用方法,均沒有出錯,錯就錯在沒有理解Vue的生命週期!!!
我們知道bus的$on的監聽應該位於$emit之前,如果在emit之前沒有創建監聽事件,那麼肯定是得不到需要的數據。因此,我通過兩個頁面來了解路由跳轉時兩個頁面的生命週期,下面給出其中一個頁面的部分代碼:
-
//頁面1
-
beforeCreate () {
-
console.group('%c%s', 'color:red', 'beforeCreate 創建前狀態===============組件1》')
-
},
-
created () {
-
console.group('%c%s', 'color:red', 'created 創建完畢狀態===============組件1》')
-
},
-
beforeMount () {
-
console.group('%c%s', 'color:red', 'beforeMount 掛載前狀態===============組件1》')
-
},
-
mounted () {
-
console.group('%c%s', 'color:red', 'mounted 掛載狀態===============組件1》')
-
},
-
beforeUpdate () {
-
console.group('%c%s', 'color:red', 'beforeUpdate 更新前狀態===============組件1》')
-
},
-
updated () {
-
console.group('%c%s', 'color:red', 'updated 更新狀態===============組件1》')
-
},
-
beforeDestroy () {
-
console.group('%c%s', 'color:red', 'beforeDestroy 破前狀態===============組件1》')
-
},
-
destroyed () {
-
console.group('%c%s', 'color:red', 'destroyed 破壞狀態===============組件1》')
-
}
當從頁面1跳轉到頁面2的時候,控制檯的打印情況如下:
從上圖便可以發現,bus第一次使用無法傳遞的原因:
在頁面1通過$emit方法傳遞數據然後跳轉路由的時候,其實頁面2的$on監聽還沒有建立,因此無法得到數據!
基於上述原因,提出的解決辦法如下:
在頁面1的beforeDestroy或者destroyed鉤子函數中emit數據,在頁面2的beforeCreate、created或者beforeMount鉤子函數中建立$on監聽事件,然後在頁面2的mounted鉤子函數中$on得到的數據賦值給頁面2的變量中。
-
//頁面1
-
beforeDestroy () {
-
bus.$emit('dataFromBus1',this.dataFromBus1);
-
},
-
//頁面2
-
beforeCreate () {
-
bus.$on('dataFromBus1',function(url){
-
bus.dataFromBus1 = url
-
});
-
},
-
mounted () {
-
this.dataFromBus1 = bus.dataFromBus1;
-
},
可以發現,第一次跳轉的時候頁面2就能夠得到傳遞的數據!!!
這個坑應該是使用bus必須會 踩到的,希望下次使用的時候能夠留個心眼!!!