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页面

你可能感兴趣的:(JavaScript,Vue,Vuex,keep-alive)