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

...
相关推荐
海石21 小时前
微信小程序开发01:XR-FRAME的快速上手
前端·增强现实·trae
叶梅树1 天前
DocsJS npmjs 自动化发布复盘(Trusted Publisher)
前端·npm
我命由我123451 天前
Element Plus - Form 的 resetField 方法观察记录
开发语言·前端·javascript·vue.js·html·html5·js
清空mega1 天前
《Vue3 项目结构详解:components、views、assets、router、stores 到底该怎么理解?》
前端·javascript·vue.js
雨雨雨雨雨别下啦1 天前
Vue——小白也能学!Day6
前端·javascript·vue.js
XPoet1 天前
AI 编程工程化:Hook——AI 每次操作前后的自动检查站
前端·后端·ai编程
難釋懷1 天前
RedisTemplate配置读写分离
前端·bootstrap·html
冰暮流星1 天前
javascript如何实现删除数组里面的重复元素
开发语言·前端·javascript
炸炸鱼.1 天前
Nginx 代理与缓存实战:正向、反向及网络层级详解
网络·nginx·缓存
网络点点滴1 天前
透传属性$attrs
前端·javascript·vue.js