Vue动态缓存KeepAlive

vue中keep-alive组件主要有三个常用的props。

  • 1,include存放的name是组件自身的name属性,只有名称匹配的组件会被缓存
  • 2,exclude,任何名称匹配的组件都不会被缓存
  • 3,max,最多可以缓存多少组件实例,一旦达到这个数字,那么缓存组件中最近没有被缓存的实例会被销毁

这里使用 include 属性实现动态缓存,include 有3种传值方式:

  1. '组件A的name,组件B的name'
  2. '正则表达式1,正则表达式2'
  3. '[组件A的name,组件B的name]'

实际开发过程中一般配合vue-router食用:

<keep-alive :include="aliveRoutes">

<router-view></router-view>

</keep-alive>

思路:通过将 aliveRoutes 加入Vuex进行状态管理,然后通过actions来动态改变aliveRoutes。具体实现如下:

javascript 复制代码
// store/async-router.js
state: {
 ...
 aliveRoutes: []    
},
mutations: {
    UPDATE_ALIVE_ROUER: (state, data) => {
      state.aliveRoutes = data
    },
},
actions: {
    ...
    addAliveRouter({ commit, state }, routerName) {
      if (!routerName) return
      const originData = state.aliveRoutes || []
      originData.push(routerName)
      const arr = Array.from(new Set(originData))
      commit('UPDATE_ALIVE_ROUER', arr)
    },
    delAliveRouter({ commit, state }, routerName) {
      const originData = state.aliveRoutes || []
      const index = originData.indexOf(routerName)
      if (!routerName || index === -1) return
      originData.splice(index, 1)
      commit('UPDATE_ALIVE_ROUER', originData)
    },
}
javascript 复制代码
// xxx.vue

...

export default {
name: 'componentA', // 注意name需要与 aliveRoutes 中保持一致
 beforeRouteLeave(to, from, next) {
    next()
    // 判断如果返回首页则移除keepalive 否则保持缓存
    if (to.path === 'index') {
    // 移除 aliveRoutes 中的 componentA 
      this.$store.dispatch('delAliveRouter', 'componentA')
    }
  },
created() {
// 初始化时增加 componentA 到 aliveRoutes 
    this.$store.dispatch('addAliveRouter', 'componentA')
},
...
}

在初始化路由时可以将路由中需要缓存的组件的name添加到 aliveRoutes 中

javascript 复制代码
import store from '@/store'

// 加载默认需要keep alive的路由
allRoutes.forEach(route => {
  const { meta, name } = route
  if (meta && meta.keepAlive) store.dispatch('addAliveRouter', name)
})

...
相关推荐
崔庆才丨静觅9 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
陌上丨10 小时前
Redis的Key和Value的设计原则有哪些?
数据库·redis·缓存
passerby606110 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了10 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅10 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅10 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅11 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment11 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅11 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊11 小时前
jwt介绍
前端