# 动态页面缓存

# 集成kepalive功能

集成案例在glink-miceo-demo子系统

# App.vue

首先在App.vue中添加keepalive,绑定动态cached参数。

<template>
  <div id="app">
    <!-- keepAlive动态缓存 -->
    <keep-alive :include="cached" max="5">
      <router-view />
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: 'App',
  computed: {
    cached() {
      return this.$store.getters['base/getCatchArr']
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# store存储配置

在store中配置存储keepalive的添加以及移除等操作

export default {
  namespaced: true,
  state: {
    // keepAlive保存缓存的列表
    catchArr: []
  },
  getters: {
    // 获取缓存列表
    getCatchArr(state) {
      return state.catchArr.toString()
    }
  },
  mutations: {
    // 对指定组件进行动态更改缓存(缓存)--组件调用该方法时,判断该组件是否存在于该缓存数组,无则添加
    iskeepAlive(state, component) {
      !state.catchArr.includes(component) && state.catchArr.push(component)
    },
    // 对指定组件进行动态更改缓存(不缓存)--组件调用该方法时,从缓存数组中删除对应的组件元素
    noKeepAlive(state, component) {
      const index = state.catchArr.indexOf(component)
      index > -1 && state.catchArr.splice(index, 1)
    }
  },
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 路由监听

在路由监听中进行keepalive的动态处理

  router.beforeEach((to, from, next) => {
    // 对组件进行动态缓存
    if (to.meta.keepAlive === true) {
      store.commit('base/iskeepAlive', to.name)
    } else if (from.meta.keepAlive === true && to.meta.clearAlive == true) {
      store.commit('base/noKeepAlive', from.name)
    }
    next()
  })
1
2
3
4
5
6
7
8
9

# router配置

name: 页面name,需和页面内编写保持一致
keepAlive: 浅显易懂,对配置的页面进行缓存
clearAlive: 用来解除页面缓存,保证下次进入可以重新执行mounted。
举例:
● 从列表页面选中某一项进入详情,返回列表页时需要保留列表的选中状态,此时需要进行缓存
● 从列表页面再返回上一级页面,比如首页。然后再次进入列表页面时需要解除缓存,保证最新数据能够重新渲染。

{
    path: '/home',
    name: 'Home',
    component: () => import('@business/views/home'),
    meta: {
      title: '首页',
      keepAlive: false, // 对特定页面进行缓存缓存
      clearAlive: true  // 对下级页面解除缓存
    }
  }
1
2
3
4
5
6
7
8
9
10