keep-Alive动态移除缓存

业务需求:后台管理快捷菜单功能,当关闭某个路由时,keep-Alive缓存重置

我们可以通过控制路由里的meta.keepAlive状态来控制是否缓存,但是当我们多个详情页指向同一路由时,这个方法便不可行,因为一旦控制了组件的keepAlive状态,我们所有指向同一组件都会受到影响,显然不符合我们的需求。

解决方法


 <keep-alive>
    <router-view ref="keepAlive" :key="$route.fullPath"></router-view>  
</keep-alive>

// 直接在keepAlive添加refs无法找到 我们可以把ref加在router-view上 通过$vnode.parent可以找到
let cacheList=this.$refs.keepAlive.$vnode.parent.componentInstance.cache

console一下cacheList

这样如果重置某个页面,我们便可以delete 某个key值就可以了

注意:如果当页面进入离开添加transition动画时,key值会变化。

解决方法:

如果路由切换时加了transition,这时候我们可以正则匹配__transition-***内容

let str = Object.keys(this.$refs.keepAlive.$vnode.parent.componentInstance.cache)
if (str.length != 0) {
    const reg = /^__transition-(\d+)-\/.*$/;
    const match = str[0].match(reg);
    this.cacheCharacterNum = match ? match[1] : null;
}

打印cacheCharacterNum

这个时候我们在进行key对比删除就可以。

完整代码:

cacheCharacter() {
// 匹配路由地址跟动画之前的数字 以防每次刷新时key里面的数字不同 导致无法找到对应的key值
  let str = Object.keys(this.$refs.keepAlive.$vnode.parent.componentInstance.cache)
     if (str.length != 0) {
         const reg = /^__transition-(\d+)-\/.*$/;
         const match = str[0].match(reg);
         this.cacheCharacterNum = match ? match[1] : null;
     }
  },
closeOther() {
    // 删除keepAlive缓存数据
    this.cacheCharacter()
    let fullPath =`__transition-${this.cacheCharacterNum}-${_this.$route.fullPath}`
    let cacheList = this.$refs.keepAlive.$vnode.parent.componentInstance.cache
    for (const key of Object.keys(cacheList)) {
        if (key !== fullPath) {
            delete this.$refs.keepAlive.$vnode.parent.componentInstance.cache[key]
        }
     }
 },

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值