有这样的需求,页面组件开启 keepAlive 之后,通过关闭标签页关闭页面成功后,再进入开启缓存的页面发现那个页面依旧是缓存的状态,这就存在问题了,看了网上别的解决方案也没发现更好的,所以就想投机取巧一下。 既然 keepAlive 组件有一个 exclude 以及 include 状态,所以可以通过动态添加组件的 exclude 来控制。
 ```template
 <keep-alive :exclude="cachedComponents">
          <router-view v-if="$route.meta.keepAlive" class="avue-view"/>
        </keep-alive>
        
```
```js
   removeComponentFromCache(componentName) {
  this.cachedComponents.push(componentName);
  this.cachedComponents = this._.uniq(this.cachedComponents)
},
addComponentFromCache(componentName) {
  const index = this.cachedComponents.indexOf(componentName);
  if (index !== -1) {
    this.cachedComponents.splice(index, 1);
  }
},
```
然后通过动态的去调用这俩方法就可以达到关闭标签页的同时把组件缓存清空,当进入页面的时候再添加到 include 中,再继续缓存组件,亲测好用。大家有啥好办法也可以分享一下啊
     1 
                    
                    Michael001      2024-09-11 18:25:50 +08:00 
                    
                    我目前也是用这种方法实现的 
                 | 
            
     2 
                    
                    Sunzehui      2024-09-12 14:00:14 +08:00 
                    
                    类似安卓式导航也是这么实现的,前进刷新后退不刷新: https://github.com/JoeshuTT/vue-page-stack-router 
                 | 
            
     3 
                    
                    Joeyyyyyyy   OP @Michael001 牛的 我之前怎么删都删不掉 只能投机取巧 
                 | 
            
     4 
                    
                    Joeyyyyyyy   OP @Sunzehui 大佬牛逼 
                 | 
            
     5 
                    
                    54xavier      2024-09-15 01:07:53 +08:00 
                    
                    我前年的项目碰到内存溢出好像就和页面缓存有关系,通过 devtools 发现页面关闭后页面仍存在于缓存中,因为新增、编辑需要可以打开多个页面,所以好像是改了 keep-alive 的 key ,把 params 参数也加了进去作为唯一标识,导致关闭的时候无法通过 path 删除对应的组件,然后就内存溢出了。 
                后来离职后好像找到有办法可以清除对应 keep-alive 中的缓存,然后能释放那些关闭页面的内存占用,不过都离职好久了,就没有义务去管之前公司的问题是否解决了。  | 
            
     6 
                    
                    he110te4m      2024-09-17 22:10:16 +08:00 
                    
                    
                 | 
            
     7 
                    
                    Joeyyyyyyy   OP @54xavier 哈哈 才回复迷弟 emm  还记得那一大段代码么 cacheClear 那块 这个办法是我后来反向思维试了一下好使才用的哈哈哈 
                 | 
            
     8 
                    
                    Joeyyyyyyy   OP @he110te4m 哈哈哈 我之前也是这么干 但是你可以用这个办法去搞 更简单了的说 
                 |