V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Joeyyyyyyy
V2EX  ›  Vue.js

vue2 缓存删除新思路

  •  
  •   Joeyyyyyyy · Sep 11, 2024 · 2601 views
    This topic created in 602 days ago, the information mentioned may be changed or developed.

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

    后来离职后好像找到有办法可以清除对应 keep-alive 中的缓存,然后能释放那些关闭页面的内存占用,不过都离职好久了,就没有义务去管之前公司的问题是否解决了。
    he110te4m
        6
    he110te4m  
       Sep 17, 2024
    我是直接去遍历 vnode 找 KeepAlive ,把里面缓存的组件给删了
    Joeyyyyyyy
        7
    Joeyyyyyyy  
    OP
       Oct 10, 2024
    @54xavier 哈哈 才回复迷弟 emm 还记得那一大段代码么 cacheClear 那块 这个办法是我后来反向思维试了一下好使才用的哈哈哈
    Joeyyyyyyy
        8
    Joeyyyyyyy  
    OP
       Oct 10, 2024
    @he110te4m 哈哈哈 我之前也是这么干 但是你可以用这个办法去搞 更简单了的说
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5699 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 06:49 · PVG 14:49 · LAX 23:49 · JFK 02:49
    ♥ Do have faith in what you're doing.