[前端] Vue3 keepalive多组件复用缓存支持 | 祭夜博客
  • 欢迎光临,这个博客颜色有点多

[前端] Vue3 keepalive多组件复用缓存支持

猿之力 msojocs 1年前 (2023-04-01) 673次浏览 已收录 0个评论 扫描二维码

原理就是修改组件的__name属性,用的时候在chchedRoute里面操作用缓存的fullPath即可

<!-- 路由出口 -->
      <el-main>
        <!-- 路由匹配到的组件将渲染在这里 -->
        <router-view v-slot="{ Component }">
          <keep-alive :include="chchedRoute">
            <component :is="wrap(Component, $route.fullPath)" />
          </keep-alive>
        </router-view>
        <!-- <router-view v-slot="{ Component }">
        </router-view> -->
      </el-main>
const cache = new Map()
/**
 * 组件复用缓存处理
 * @param cmp 组件
 * @param fullPath 全路径
 */
const wrap = (cmp: any, fullPath: string) => {
  // 不在缓存列表直接返回组件
  if (!chchedRoute.value.includes(fullPath)) return cmp
  if (cache.has(fullPath)) {
    cmp.type = cache.get(fullPath)
  }
  else {
    const t: Record<string, any> = {}
    for (const key of Object.keys(cmp.type))
      t[key] = cmp.type[key]
    cmp.type = t
    cmp.type.__name = fullPath
    cache.set(fullPath, cmp.type)
  }
  return cmp
}

祭夜の咖啡馆 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:[前端] Vue3 keepalive多组件复用缓存支持
喜欢 (1)
[1690127128@qq.com]
分享 (0)
发表我的评论
取消评论
OwO表情
贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址