在Vue中切換路徑時,如果下一個路由與當前頁面共用同一個組件,Vue會復用當前組件,不會重新創建一個。這就導致組件的生命周期函數如mounted, created等不會被觸發,頁面看起來就像什么都沒發生一樣。
在vue-router 2.2版本之后,可以使用beforeRouteUpdate這個導航守衛來監聽同一個路由更新參數時的情況,但這個守衛并不會在不同路由共用同一組件時觸發。
舉例來說,有下面這一組路由:
const route = [
{
path: '/item/:id/edit',
name: 'editItem',
component: Editor,
}, {
path: '/item/create',
name: 'createItem',
component: Editor,
}
];
當從/item/22/edit
切換到/item/11/edit
時,會觸發beforeRouteUpdate
。
但如果從/item/22/edit
切換到/item/create
時,并不會觸發beforeRouteUpdate
。
解決方法
如果上面兩個狀況都要監聽到,可以選擇監聽$route
參數,當url發生變化時,都會引起$route
的改變,在監聽函數里執行需要的操作。
watch: {
'$route': function() {
if (this.$route.name === 'createItem') {
...
} else if (this.$route.name === 'editItem') {
...
}
}
}