vue3 keep-alive多个路由使用同一个组件的缓存问题

上一篇文章讲到当打开多个内页签页面, keep-alive缓存每个页面,导致内存溢出。顾添加max=10, 在此基础上希望每次关闭内页签页面时,能够手动的清除当前页面的缓存。

我们可以通过改变exclude来实现手动清除keep-alive缓存。 exclude需要的是组件的名称。

这里就有一个问题:我们多个编辑页面公用一个组件, 但我们会有多个缓存,也就是当打开多个编辑页面, 当关闭其中一个编辑页的时候, 传入对应组件的name, 会把所有的编辑页面的缓存都移除。

这时该怎么解决呢?我们可以给不同的编辑页面设置一个唯一的组件名称, 具体实现如下:

html 复制代码
<router-view v-slot="{ Component }">
      <div class="app-main-height">
        <keep-alive :max="10" :exclude="excludes">
          <component :is="formatComponentInstance(Component, $route)" :key="$route.path" />
        </keep-alive>
      </div>
    </router-view>
    
js 复制代码
// 用来存已经创建的组件
  const wrapperMap = new Map();
  // 将router传个我们的组件重新换一个新的组件,原组件包里面
  function formatComponentInstance(component, route) {
    let wrapper;
    if (component) {
      const wrapperName = route.path;
      if (wrapperMap.has(wrapperName)) {
        wrapper = wrapperMap.get(wrapperName);
      } else {
        wrapper = {
          name: wrapperName,
          render() {
            return h(component);
          },
        };
        wrapperMap.set(wrapperName, wrapper);
      }
      return h(wrapper);
    }
  }
相关推荐
易朵朵15 小时前
CSS 格式化上下文
css·vue.js
雪芽蓝域zzs16 小时前
第6节:远程搜索弹窗(remote 模式),弹窗滚动加载分页
vue.js·elementui
Highcharts.js17 小时前
图表开发实战总结| 7 条“黄金法则”与“性能铁律”
前端·javascript·vue.js·编辑器·时序数据库·highcharts
Wx-bishekaifayuan20 小时前
springboot陨石鉴收系统96265-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spring·课程设计
FYKJ_201021 小时前
springboot家政服务平台66766-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·mysql·spark·课程设计
墨鱼老师21 小时前
Go+Gin+Vue 毕设项目:Gin 框架搭建后端基础接口实战
vue.js·golang·go·gin·前后端分离·计算机毕业设计·go 后端
ym hyd 1111 天前
试题库管理系统源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·毕设
雪芽蓝域zzs1 天前
第4节:el-select 弹窗事件控制(打开 / 关闭、选中事件、弹窗滚动事件)
vue.js·elementui
web打印社区2 天前
HTML5 静默打印:前端页面怎么调用打印机且尽量不弹窗
前端·javascript·vue.js·pdf·html·html5
雪芽蓝域zzs2 天前
第3节:el-select 弹窗定位、滚动穿透与挂载容器(popper-append-to-body /teleported)
vue.js·elementui