vue頁面緩存--動態keep-alive

需要實現的場景

當 A頁面除了返回上級頁面以外,跳到其他頁面均緩存A頁面內容

實現思路

  1. 使用keep-alive的include屬性,將需要緩存的頁面加入include數組中
  2. 使用vuex保存需要緩存的頁面集合
  3. 在頁面跳轉時使用導航守衛判斷路由跳轉頁面
  4. 調用vux中的方法修改include集合

代碼實現如下

App.vue
<template>
  <keep-alive :include="keepAlive" >
    <router-view/>
  </keep-alive>
</template>
<script>
  export default {
    data() {
      return {}
    },
    computed: {
      keepAlive() {
        return this.$store.state.keepAlive.join(',')
      }
    }
  }
</script>

Store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    keepAlive: []
  },
  mutations: {
    onKeepAlive (state, keepAlive) {
      state.keepAlive = keepAlive
    }
  },
   actions: {
    onKeepAlive ({ commit }, keepAlive) {
      commit('onKeepAlive', keepAlive)
    }
  }
})
A.vue
beforeRouteLeave(to, from, next) {
   if (to.path.indexOf('B') == -1) {
        this.$store.dispatch('onKeepAlive', ['A'])
    }
    next()
}
//判斷跳轉路由是否爲B,爲B不緩存,其他頁面均緩存A頁面
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章