vue keep-alive 多级路由 关闭标签清除缓存

本文介绍了在Vue中处理多级路由缓存的问题,特别是如何在主路由上添加keep-alive并实现特定页面缓存。通过监听页面离开事件并在main.js中操作缓存列表,确保关闭标签时正确清除缓存。同时,文章提到了在激活和停用组件时使用activated和deactivated的方法,以更新页面数据。此外,还分享了在添加和删除标签时更新缓存列表的策略。
摘要由CSDN通过智能技术生成

背景:特定页面添加缓存,并且在关闭标签后需要清除缓存。

多级路由添加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是页面离开。

这样基本上就可以实现上面的需求了,也查找了很多方法,最终也是站在了巨人的肩膀上,好了希望能帮到你们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值