vue3 使用KeepAlive缓存,多个路由使用同一个组件

3 篇文章 0 订阅

项目使用KeepAlive缓存页面,页面内容根据参数来显示区分,所以出现多个路由指向同一个组件,缓存就不生效了。

解决思路

  • 1、动态路由渲染时,给组件套一个空壳,设置不一样的name。
  • 2、动态路由渲染时,复制一个仅name不同的组件,或者修改组件的name。(未使用,仅验证过可行性)

思路一实现:

// dynamicRouteComponet.tsx
import { defineComponent, defineAsyncComponent } from 'vue'

export const dynamicRouteComponet = (componentOption, routeName) => {
  return defineComponent({
    name: routeName,
    components: {
      comp: defineAsyncComponent(componentOption)
    },
    setup() {
      return () => {
        return <comp></comp>
      }
    }
  })
}
data.component = dynamicRouteComponet(comModule, route.name)

思路二实现

//组件地址必须是字符串,如果是动态的可以使用if判断,要给组件仅呈现一个根元素,不然会有警告异常,直接修改组件的name不会有警告
data.component = () => createCustomComponent(import('../views/...'), route.name)

//警告信息
//Component "default" in record with path "/dashboard/workplace" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.
//复制组件
import { h, onMounted, shallowRef } from 'vue'
export const createCustomComponent = (component, name) => {
  return {
    name,
    setup() {
      const comp: any = shallowRef(null)
      onMounted(async () => {
        if (component instanceof Promise) {
          try {
            const module = component
            console.log(module)
            comp.value = (await module)?.default
          } catch (error) {
            console.error(`can not resolve component ${name}, error:`, error)
          }
          return
        }

        comp.value = component
      })

      return () => {
        console.log(comp.value)
        return comp.value ? h(comp.value) : null
      }
    }
  }
}
data.component = () => dynamicComponent(import('../views/Dashboard/Workplace.vue'), route.name)
//修改组件名称
export const dynamicComponent = (component, routeName) => {
  return component.then((comp) => {
    if (comp && comp.default) {
      return { ...comp.default, name: routeName }
    }
    return comp
  })
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值