- 清除指定页面组件缓存,只适用于vue2的版本。
- 适用场景:
- 在特定情况下,需要清除被
keep-alive
包裹的组件缓存;
- 使用方法:可以将如下的方法在全局挂载,在需要清除缓存的逻辑中直接调用即可。
function removeCacheFn(node, name) {
console.log(node);
if (!node.$vnode) return;
if (node.$vnode.parent) {
handleRemoveCacheFn(node, name);
} else {
if (node.$vnode.componentOptions.tag !== "App") {
removeCacheFn(node.$parent, name);
} else {
return;
}
}
}
function handleRemoveCacheFn(that, name) {
if (!(that.$vnode && that.$vnode.parent)) return;
let keepAlive = that.$vnode.parent;
let cache = keepAlive.componentInstance.cache;
let keys = keepAlive.componentInstance.keys;
let delKey = "";
for (const i in cache) {
if (Object.hasOwnProperty.call(cache, i)) {
if (cache[i].name === name) {
delKey = cache[i].tag.split("-")[2];
let index = keys.indexOf(delKey);
if (index > -1) {
keys.splice(index, 1);
}
cache[i] = null;
}
}
}
}
export default {
removeCacheFn,
};