前言
关于vue keep-alive标签,缓存后每次打开的是缓存后的页面,必须强制刷新页面才会更新,tab页面的后台管理系统,现在有需求是每次关闭页签,从菜单进入后,需要重新刷新页面
万事先百度
百度结果,是需要在每个页面离开前监听beforeRouteLeave 事件,相关代码,我复制一下
beforeRouteLeave:function(to, from, next){
// 增加离开路由时清除keep-alive
if (from && from.meta.rank && to.meta.rank && from.meta.rank == to.meta.rank)
{//此处判断是如果返回上一层,你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
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();
},
来自
https://www.jb51.net/article/219189.html
但是我的代码都写了大半了,又要每个页面去改,真是不实际,有没有办法全局更改,判断,删除标签的时候去掉缓存
直接上代码
- dom
<keep-alive> <router-view :key="key" ref="routerView" /> </keep-alive>
想着在这个页面通过ref去拿到当前页面的vue实例,这个办法是可以的
- 监听路由跳转,只要当前实例里的缓存caches在delBeforeViews数组里找不到,就删除掉缓存 只要是打开新页面就去处理一次删除缓存操作
watch: {
$route() {
const This = this;
const vueInstance = this.$refs.routerView;
console.log(vueInstance);
const caches = vueInstance.$vnode.parent.componentInstance.cache;
Object.keys(caches).map((key) => {
if (!This.delBeforeViews.find((item) => item.path == key)) {
This.removeCache(caches[key].componentInstance);
}
});
},
},
methods: {
removeCache(vueInstance) {
const key =
vueInstance.$vnode.key ??
vueInstance.$vnode.componentInstance.Ctor.cid +
(vueInstance.$vnode.componentInstance.tag
? `::${vueInstance.$vnode.componentInstance.tag}`
: "");
const cache = vueInstance.$vnode.parent.componentInstance.cache;
const keys = vueInstance.$vnode.parent.componentInstance.keys;
if (cache[key]) {
vueInstance.$destroy();
delete cache[key];
const index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
},
},
delBeforeViews是什么,这个是store里的一个值,保存的是打开新的tab页签前已打开的tab页面的key值(不包括新打开的页签)
好啦,真的是完美