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

相关推荐
小七-七牛开发者8 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
ofoxcoding16 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen16 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans16 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时16 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚16 天前
Linux——Redis
数据库·redis·缓存
小挪号底迪滴16 天前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存
闪电悠米16 天前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Saniffer_SH17 天前
【高清视频】Gen6 服务器还没到,Gen6 SSD 怎么测?Emily 现场演示三种测试环境
人工智能·驱动开发·测试工具·缓存·fpga开发·计算机外设·压力测试