VUE router-view key 屬性解釋


router-view 作用, 你可以 router-view 當做是一個容器,它渲染的組件是你使用 vue-router 指定的。

<template>
  <section class="app-main">
    <transition name="fade-transform" mode="out-in">
      <router-view :key="key" />
    </transition>
  </section>
</template>

<script>
export default {
  name: 'AppMain',
  computed: {
    key() {
      return this.$route.fullPath
    }
  }
}
</script>

這里router-view 有一個key的屬性,這個key的屬性作用是:

1. 不設置 router-view 的 key 屬性

由於 Vue 會復用相同組件, 即 /page/1 => /page/2 或者 /page?id=1 => /page?id=2 這類鏈接跳轉時, 將不在執行created, mounted之類的鈎子, 這時候你需要在路由組件中, 添加beforeRouteUpdate鈎子來執行相關方法拉去數據

相關鈎子加載順序為: beforeRouteUpdate

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