在使用keepAlive缓存时, 如果 A 页面 --> B 页面 做了操作 --> C页面
再从 C页面返回 --> B页面 --> A 页面 页面除了点击返回和点击进入无其他操作
再次从 A 页面 --> B 页面 --> C 页面 页面除了点击返回和点击进入无其他操作
从C 页面 -- > B 页面时 B页面保留了上一次进入到B页面的缓存
解决方法 :
首先 : 获取到 this 实例对象

找到 vue实例上的 this.$vnode 属性 和 this.$vnode.parent 属性

查看 this.$vnode 下的 componentInstance.cache 的变化

查看并记录 this.$vnode.key 的变化

记录 this.$vnode.componentOptions.Ctor.cid 的变化

查看 this.$vnode.componentOptions.tag 的值 变化

通过以上方式的帮助 使用以下代码可解决
//获取vue实例对象上的$vnode属性
let vnode = this.$vnode;
let parentVonde = vnode && vnode.parent;
if (
parentVonde &&
parentVonde.componentInstance &&
parentVonde.componentInstance.cache
) {
var key =
vnode.key == null
? vnode.componentOptions.Ctor.cid +
(vnode.componentOptions.tag
? `::${vnode.componentOptions.tag}`
: "")
: vnode.key;
var cache = parentVonde.componentInstance.cache;
var keys = parentVonde.componentInstance.keys;
if (cache[key]) {
this.$destroy();
// remove key
if (keys.length) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
cache[key] = null;
}
}
在不需要做缓存的页面时 在beforeRouteLeave 里 做 移除缓存处理
案例 :
//这是当前页配置的路由
{
path: '/myDeal/:title',
component: myDeal,
meta:{
keepAlive:true
}
},
//需要进行缓存的页面 使用组件内路由守卫beforeRouteLeave
beforeRouteLeave(to, from, next) {
//判断将要去的组件名或者组件路径
if (to.name == "orderDetails") {
//在当前页进行设置缓存为true
from.meta.keepAlive = true;
} else {
// 如果是去往其他页面就执行一下操作
// 清除上一次保留的keepAlive缓存
let vnode = this.$vnode;
let parentVonde = vnode && vnode.parent;
if (
parentVonde &&
parentVonde.componentInstance &&
parentVonde.componentInstance.cache
) {
var key =
vnode.key == null
? vnode.componentOptions.Ctor.cid +
(vnode.componentOptions.tag
? `::${vnode.componentOptions.tag}`
: "")
: vnode.key;
var cache = parentVonde.componentInstance.cache;
var keys = parentVonde.componentInstance.keys;
if (cache[key]) {
this.$destroy();
// remove key
if (keys.length) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
cache[key] = null;
}
}
}
next();
},
该博客详细介绍了在Vue中使用keepAlive缓存时遇到的问题及解决方案。当从A页面->B页面->C页面,然后回退到B页面,B页面会保留之前的缓存。为避免这种情况,可以通过检查和操作Vue实例的$vnode属性来手动清除不需要的缓存。在beforeRouteLeave路由守卫中,根据目标页面判断是否需要清除缓存,从而实现精确的缓存控制。
2822

被折叠的 条评论
为什么被折叠?



