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)
})

...
相关推荐
@大迁世界6 小时前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊8 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome8889 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌9 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易9 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常10 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师10 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么11 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒11 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07611 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端