V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Joeyyyyyyy
V2EX  ›  Vue.js

vue2 缓存删除新思路

  •  
  •   Joeyyyyyyy · 6 天前 · 602 次点击

    有这样的需求,页面组件开启 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 中,再继续缓存组件,亲测好用。大家有啥好办法也可以分享一下啊
    
    6 条回复    2024-09-17 22:10:16 +08:00
    Michael001
        1
    Michael001  
       6 天前
    我目前也是用这种方法实现的
    Sunzehui
        2
    Sunzehui  
       5 天前
    类似安卓式导航也是这么实现的,前进刷新后退不刷新: https://github.com/JoeshuTT/vue-page-stack-router
    Joeyyyyyyy
        3
    Joeyyyyyyy  
    OP
       4 天前
    @Michael001 牛的 我之前怎么删都删不掉 只能投机取巧
    Joeyyyyyyy
        4
    Joeyyyyyyy  
    OP
       4 天前
    @Sunzehui 大佬牛逼
    54xavier
        5
    54xavier  
       2 天前
    我前年的项目碰到内存溢出好像就和页面缓存有关系,通过 devtools 发现页面关闭后页面仍存在于缓存中,因为新增、编辑需要可以打开多个页面,所以好像是改了 keep-alive 的 key ,把 params 参数也加了进去作为唯一标识,导致关闭的时候无法通过 path 删除对应的组件,然后就内存溢出了。

    后来离职后好像找到有办法可以清除对应 keep-alive 中的缓存,然后能释放那些关闭页面的内存占用,不过都离职好久了,就没有义务去管之前公司的问题是否解决了。
    he110te4m
        6
    he110te4m  
       42 分钟前
    我是直接去遍历 vnode 找 KeepAlive ,把里面缓存的组件给删了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2385 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 14:52 · PVG 22:52 · LAX 07:52 · JFK 10:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.