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要一致

相关推荐
wdfk_prog17 小时前
ROS教程10:从 gtest 到 rostest——Unit Test、Node 集成测试、rosbag 与 rqt 验证闭环
运维·缓存·docker·容器·ros
程序猿乐锅1 天前
【黑马点评 | 第四篇】Redis缓存雪崩
java·数据库·spring boot·redis·缓存
HanhahnaH1 天前
Redis单线程和Tair多线程架构设计对比
分布式·缓存
wdfk_prog2 天前
ROS教程07:从 ros::start() 顺着源码读懂 Master、XML-RPC 与 Topic 注册发现
运维·缓存·docker·容器·ros
Escalating_xu2 天前
【内存管理发展史】从 8086 实模式到分页:CPU 如何把虚拟地址变成物理地址
linux·缓存
wdfk_prog2 天前
用 Git Submodule + Sparse Checkout 管理 RT-Thread:内核、BSP、第三方库与业务代码分层实践
运维·缓存·docker·容器·ros
努力努力再努力wz2 天前
【Docker入门系列】镜像为什么能复用?一文吃透 Docker Image、Registry、运行时架构与常用命令
缓存·docker·容器
shark-chili2 天前
关于AI辅助编程的认知
数据库·人工智能·redis·macos·缓存
oioihoii2 天前
在 Kubernetes 上管好数据库:金仓 KES-Operator 正式落地
缓存
wdfk_prog2 天前
ROS教程06:ROS1 Node 启动与停止流程
运维·缓存·docker·容器·ros