一、概要
1.本文主要针对web端后台系统打开指定页面tab,关闭该tab后清楚keep-alive中页面缓存
2.结合vuex和vueRouter应用
二、代码实现
1.关闭tab
tabs.vue
...mapMutations('app', ['clearCaches'])
this.clearCaches({clearCachesFlag:true,view:curRoute})
复制代码
store.js
state: {
clearCachesFlag:false,curRoute:{}
},
mutations:{
clearCaches(state,{clearCachesFlag,curRoute}){
state.clearCachesFlag=clearCachesFlag
state.curRoute=curRoute
}
}
复制代码
2.清除keep-alive对应缓存key
app.vue
watch:{
'$store.state.app.removeCaches'(val){
if(val){
this.removeCache(this.curView)
}
}
},
// 移除keep-alive缓存
removeCache(view = {}) {
let vnode = this.getVnode();
if (!vnode) return false;
let componentInstance = vnode.parent.componentInstance;
// 这个key是用来获取前缀用来后面正则匹配用的
let keyStart = vnode.key.split('/')[0];
let thisKey = `${keyStart}${view.fullPath}`;
let regKey = `${keyStart}${view.path}`;
this.closeSelectedTag({ componentInstance, thisKey, regKey });
},
getVnode() {
// 判断子集非空
if (this.$children.length == 0) return false;
let vnode;
for (let item of this.$children) {
// 如果data中有key则代表找到了keep-alive下面的子集,这个key就是router-view上的key
if (item.$vnode.data.key) {
vnode = item.$vnode;
break;
}
}
return vnode ? vnode : false;
},
closeSelectedTag({ componentInstance, regKey }){
let reg = new RegExp(`^${regKey}`);
Object.keys(componentInstance.cache).forEach((key, i) => {
if (regKey===key) {
// 1 销毁实例
if (componentInstance.cache[key]) {
componentInstance.cache[key].componentInstance.$destroy();
}
// 2 删除缓存
delete componentInstance.cache[key];
// 3 移除key中对应的key
componentInstance.keys.splice(i, 1);
}
});
this.clearCaches(false)
},
...mapMutations('app', ['clearCaches'])
复制代码
总结
1. 包裹动态组件时,会缓存不活动的组件实例,所以当关闭页面混存key还在
2.手动清除指定页面缓存key,可达到打开之前关闭页面实现刷新效果
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END