写这篇博文的目的是整理思路,KeepAlive动态修改目前有局限性,只使用改变 状态修改页面是否缓存,无法彻底删除上次缓存。
我们是在app.vue 添加keepAlive缓存,通过路由配置开关
{
path: "/enterpriseApply",
name: "enterpriseApply",
component: enterpriseApply,
meta: {
showFooter: false,
keepAlive: true
}
}
<template>
<div class="body_wrap">
<keep-alive >
<router-view v-if="this.$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!this.$route.meta.keepAlive"></router-view>
<footerNav v-if="$route.meta.showFooter"></footerNav>
</div>
</template>
默认KeepAlive已熟悉 , 不熟悉的可以看下官网。
KeepAlive 推荐使用include和 exclude 添加和移除缓存组件,需要Vuex的配合,我们项目比较小,没有需求大量使用Vuex,集成过于冗余。
KeepAlive存在问题:提交完表单之后,下一次提交的时候,如何删除上一次缓存问题。
解决方案(尝试):
总结:尝试了几种方案,问题点是在于,删除缓存,下次不会显示,第三种可行。
路由守卫离开函数{
if 离开去缓存的页面 {
本页面keepAlive 打开
}else{
销毁这次缓存
}
}
路由守卫进入函数{
打开本页面的keepAlive
}
注意:因为上次离开的时候,删除了缓存,keepAlive 属性进来的时候还需要更改。
beforeRouteLeave (to, from, next) {
if (to.name === "agree") {
from.meta.keepAlive = true
console.log(from.meta.keepAlive)
} else {
if (this.$vnode && this.$vnode.data.keepAlive) {
if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache) {
if (this.$vnode.componentOptions) {
var key = this.$vnode.key == null
? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
: this.$vnode.key;
var cache = this.$vnode.parent.componentInstance.cache;
var keys = this.$vnode.parent.componentInstance.keys;
if (cache[key]) {
if (keys.length) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
delete cache[key];
}
}
}
}
this.$destroy();
}
next();
},
beforeRouteEnter (to, from, next) {
if (to.name === "enterpriseApply") {
to.meta.keepAlive = true
}
next();
},
这样虽然解决了强制删除缓存的目的,感觉还是不够优雅,是否可以不借助Vuex动态的修改Include和exclude 来实现呢?有更好的方法,欢迎留言指教。