vue keep-alive 如何设置动态的页面缓存
页面有时候需要设置缓存,比如填写信息页面 选择部门人员时跳转到组织架构页面,选择完毕之后返回信息填写页面,再次点击选人员页面需要保存之前已选的状态,但是在保存信息后需要将缓存状态清除,代码如下
1.在vuex中添加路由缓存列表
代码如下
const state = {
include: [], // 路由缓存列表
}
const mutations = {
// 添加路由缓存
SETINCLUDELIST(state, payload) {
state.include.push(payload)
},
// 删除路由缓存
REMOVEINCLUDELIST(state, payload) {
let index = state.include.indexOf(payload)
state.include.splice(index, 1)
},
// 清空缓存路由
CLEARINCLUDELIST(state) {
state.include = []
},
}
const actions = {}
export default {
namespaced: true,
state,
mutations,
actions,
}
2.在App.vue文件里给 keep-alive 添加 include属性并且进行监听
代码如下
<template>
<div id="app">
<!-- 一级路由出口 -->
<keep-alive :include="include">
<router-view v-if="$route.meta.keepAlive"></router-view
></keep-alive>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
watch: {
$route: {
handler(to, from) {
to.matched.forEach((item) => {
// 需要缓存的页面 且 缓存列表里面没有当前页面的 执行缓存操作
if (item.meta.keepAlive && !this.include.includes(item.name)) {
this.$store.commit('app/SETINCLUDELIST', item.name)
}
})
// 首页标签切换的时候 删除前一个页面的缓存
if (
to.path.includes('layout') &&
from.path.includes('layout') &&
this.include.includes(from.name)
) {
this.$store.commit('app/REMOVEINCLUDELIST', from.name)
}
},
},
},
computed: {
...mapState({
include: (state) => state.app.include,
}),
},
}
</script>
3.使用。
首先需要在路由文件里给页面加缓存属性,即 keepAlive: true
其次,如果页面需要清除缓存状态,代码如下
注意:要删除的路由名称一定要和页面组件的name一致
这样就可以了