背景:特定页面添加缓存,并且在关闭标签后需要清除缓存。
多级路由添加keep-alive 只给二级路由添加是没有效果的,需要在主路由上也添加keep-alive,加上以后又出现个问题,使用include无法实现单独页面添加缓存的问题。的确是有点恶心。
解决方法:
1.在main.js里面添加页面离开的监听方法,并获取到缓存(因为只有这里才能看到缓存)。找到不需要做缓存的页面将缓存删除掉。配置需要缓存的页面然后进行判断。我是用的store。
Vue.mixin({
beforeRouteLeave(to,from,next){
if(!this.$vnode.parent){
next()
return
}
store.state.userinfo.cacheList = this.$vnode.parent.componentInstance.cache;
let key = this.$vnode.key;
let pageName = this.$vnode.tag.split('-').pop();
let index = store.state.userinfo.isAlive.indexOf(pageName);
if(index<0){
delete this.$vnode.parent.componentInstance.cache[key]
// this.$vnode.parent.componentInstance.cache.splice(index,1);
this.$destroy()
}else{
if(!store.state.userinfo.keepAlivePages.includes(from.name)){
delete this.$vnode.parent.componentInstance.cache[key]
// this.$vnode.parent.componentInstance.cache.splice(index,1);
this.$destroy()
}
}
next();
}
});
2.在添加标签的地方将需要缓存的页面路由添加到你的缓存的列表里面,用作在页面离开的时候判断是否需要清除缓存。这里存在一个问题,当我不是当前选中的时候不会触发页面离开的事件,这就需要我们单独添加一个页面跳转的过程,这个是我自己想到的,有更好的方法的希望大佬能够分享,
//添加缓存列表
this.tagsList.map((t) => {
if (this.$store.state.userinfo.isAlive.includes(t.name) &&
!this.$store.state.userinfo.keepAlivePages.includes(t.name)) {
this.$store.state.userinfo.keepAlivePages.push(t.name)
}
})
//关闭标签 从缓存列表中删除该页面 不是当前选中的在缓存列表中的需要回跳一下
let pindex = this.$store.state.userinfo.keepAlivePages.indexOf(delItem.name);
if (pindex < 0) {
} else {
if(!this.isActive(delItem.path)){
this.$router.push(delItem.path);
}
this.$store.state.userinfo.keepAlivePages.splice(pindex, 1)
}
3.activated和deactivated的使用,在keep-alive中需要修改页面数据的时候需要调用这两个方法,activated是页面进入,deactivated是页面离开。
这样基本上就可以实现上面的需求了,也查找了很多方法,最终也是站在了巨人的肩膀上,好了希望能帮到你们。