keepalive路由缓存实现前进刷新后退缓存

1.在app.vue中配置全局的keepalive并用includes指定要缓存的组件路由name名字数组

javascript 复制代码
<keep-alive :include="keepCachedViews">
      <router-view />
    </keep-alive>

computed: {
    keepCachedViews() {
      console.log('this.$store.getters.keepCachedViews', this.$store.getters.keepCachedViews)
      return this.$store.getters.keepCachedViews
    }
  },

2.在vuex中/store/module存储要缓存的组件路由数组

javascript 复制代码
state: {
    keepCachedViews: []
  },
mutations: {
//增加方法
    UPDATE_KEEPCACHEDVIEWS: (state, view) => {
      console.log('增加缓存------', view)
      if (state.keepCachedViews.includes(view.name)) return
      if (!view.meta.noCache) {
        state.keepCachedViews.push(view.name)
      }
    },
//删除方法
    DELET_KEEPCACHEDVIEWS: (state, view) => {
      console.log('删除缓存------', view)
      const index = state.keepCachedViews.indexOf(view.name)
      index > -1 && state.keepCachedViews.splice(index, 1)
    },
},
actions: {
    updateKeepcachedViews({ commit }, views) {
      commit('UPDATE_KEEPCACHEDVIEWS', views)
    },
    deleteKeepcachedViews({ commit }, views) {
      commit('DELET_KEEPCACHEDVIEWS', views)
    },
}

3.在vuex getter.js中获取keepCachedViews

javascript 复制代码
export default {
  keepCachedViews: state => state.ibps.app.keepCachedViews// 缓存的组件
}

4.在组件内守卫中判断什么时候缓存该组件

注意:路由离开时再添加缓存不生效 ,所以我想到的解决办法是在进入要缓存的页面前,先默认将页面添加到缓存数组中,在离开时再判断是否要缓存这个组件

ps:路由前置守卫中没有this,所以要用vm

javascript 复制代码
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.$store.dispatch('ibps/app/updateKeepcachedViews', to)
      return true
    })
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != 'ylnlDataTemplateList') {
      this.$store.dispatch('ibps/app/deleteKeepcachedViews', from)
    }
    next()
  },

注意:路由中的name和组件的name要一致

相关推荐
海梨花2 分钟前
【从零开始学习Redis】项目实战-黑马点评D2
java·数据库·redis·后端·缓存
2301_793086871 天前
Redis 04 Reactor
数据库·redis·缓存
189228048611 天前
NY243NY253美光固态闪存NY257NY260
大数据·网络·人工智能·缓存
青鱼入云1 天前
redis怎么做rehash的
redis·缓存
FFF-X1 天前
Vue3 路由缓存实战:从基础到进阶的完整指南
vue.js·spring boot·缓存
夜影风2 天前
Nginx反向代理与缓存实现
运维·nginx·缓存
编程(变成)小辣鸡2 天前
Redis 知识点与应用场景
数据库·redis·缓存
菜菜子爱学习3 天前
Nginx学习笔记(八)—— Nginx缓存集成
笔记·学习·nginx·缓存·运维开发
魏波.3 天前
常用缓存软件分类及详解
缓存
yh云想3 天前
《多级缓存架构设计与实现全解析》
缓存·junit