[js]vue中 給router-view 元件的 繫結 key 的原因
阿新 • • 發佈:2020-08-06
vue中 給router-view 元件的 繫結 key 的原因
1. 不設定 router-view 的 key 屬性
由於 Vue 會複用相同元件, 即 /page/1 => /page/2 或者 /page?id=1 => /page?id=2 這類連結跳轉時, 將不在執行created, mounted之類的鉤子, 這時候你需要在路由元件中, 新增beforeRouteUpdate鉤子來執行相關方法拉去資料
相關鉤子載入順序為: beforeRouteUpdate
官網文件
const User = { template: '...', watch: { $route(to, from) { // 對路由變化作出響應... } } }
或者
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
2. 設定 router-view 的 key 屬性值為 $route.path
從/page/1 => /page/2, 由於這兩個路由的$route.path並不一樣, 所以元件被強制不復用, 相關鉤子載入順序為:
beforeRouteUpdate => created => mounted
從/page?id=1 => /page?id=2, 由於這兩個路由的$route.path一樣, 所以和沒設定 key 屬性一樣, 會複用元件, 相關鉤子載入順序為:
beforeRouteUpdate
3. 設定 router-view 的 key 屬性值為 $route.fullPath
從/page/1 => /page/2, 由於這兩個路由的$route.fullPath並不一樣, 所以元件被強制不復用, 相關鉤子載入順序為:
beforeRouteUpdate => created => mounted
從/page?id=1 => /page?id=2, 由於這兩個路由的$route.fullPath並不一樣, 所以元件被強制不復用, 相關鉤子載入順序為:
beforeRouteUpdate => created => mounted