keep-alive指定條件緩存的坑


需求

  • 編輯頁面可以跳轉至預覽頁面,預覽頁面返回是編輯頁面不會重新加載
  • 列表頁或查看頁面進入編輯頁面的頁面需要重新加載

一下a b c 分別為:
a 列表頁面
b 編輯頁面
c 預覽頁面

走過的彎路

錯誤的處理方式:
a頁面:

// 從列表頁進入的時候將詳情的keepAlive設置為false
beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = false
    next()
  },

b頁面:

beforeRouteEnter(to, from, next) {
    next(vm => { // 此時還沒有this, 通過傳入的vm, 可以充當this使用
      if (from.name === 'c') {
            // 如果從c頁面過來則為true
        vm.$route.meta.keepAlive = true
      }
    })
  },
beforeRouteLeave(to, from, next) {
    if (to.name === 'c') {
      this.$route.meta.keepAlive = true
    } else {
      this.$route.meta.keepAlive = false
    }
    console.log(this.$route.meta.keepAlive, 'this.$route.meta.keepAlive=')
    next()
  },
activated() {
    // 此方法在頁面緩存時會被調用,根據路由元信息決定是否重新加載數據。不加載則是上次填寫完的數據
    if (!this.$route.meta.keepAlive) {
      this.init()
    }
  },

上面處理的導致的問題是: 第一次從a頁面進入b, 再有b進入c時, b並沒有被緩存, 因為a進入b的時候b的keepAlive為false,
從c進入b之后, b的keepAlive才變成true, 才會緩存組件.

最后發現是我想的復雜了, b的keepAlive初始值為true, 剩下的只需要判斷b頁面離開時要去a還是去c, 如果去a,則為false,不進行緩存, 去c則為true, 緩存b組件

正確代碼實現

// 編輯頁面所在的<router-view></router-view>所在的文件
// 注意: 不能和<transition></transition>一起使用
<keep-alive>
    <router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />


// 編輯頁面注冊路由的地方配置meta, 通過keepAlive控制適合緩存組件
{
    path: 'compile',
    component: () => import('@/views/project/compile'),
    name: 'compile',
    meta: {
        keepAlive: true,
        title: '方案編輯',
    }
}

// b頁面
beforeRouteLeave(to, from, next) {
    if (to.name === 'c') {
      this.$route.meta.keepAlive = true
    } else {
      this.$route.meta.keepAlive = false
      this.clear()
    }
    console.log(this.$route.meta.keepAlive, 'this.$route.meta.keepAlive=')
    next()
  },
activated() {
    // 此方法在頁面緩存時會被調用,根據路由元信息決定是否重新加載數據。不加載則是上次填寫完的數據
    console.log(this.$route.meta.keepAlive, 'this.$route.meta.keepAlive======')
    if (!this.$route.meta.keepAlive) {
      this.init()
    }
  }


免責聲明!

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



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