[js]vue中 給router-view 組件的 綁定 key 的原因


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM