問題:當使用路由參數時,例如從
/content?id=1
到content?id=2
,此時原來的組件實例會被復用
。這也意味着組件的生命周期鈎子不會再被調用
,此時vue應該如何響應路由參數
的變化?
參考答案:
復用組件時,想對路由參數的變化
作出響應的話, 可以watch (監測變化) $route 對象
:
const User = { template: '...', watch: { '$route' (to, from) { // 對路由變化作出響應... } } }
或者使用 2.2
中引入的 beforeRouteUpdate
守衛:
const User = { template: '...', beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() } }
beforeRouteUpdate適用場景
在進入一個路由頁面的時候,再次點擊進入這個路由頁面並且多傳遞一個參數的時候,created里 不會觸發,思考了幾分鍾,想到是路由沒有變化只是更新了參數,就想到了beforeRouteUpdate
beforeRouteUpdate是路由更新時觸發的鈎子函數
有三個參數 to,from ,next
beforeRouteUpdate(to,from,next){ let a = to.query.a next() }
to表示去哪里,跳轉到那個頁面
from 表示 來自那個頁面
next() 表示繼續執行頁面,要加上的