原理就是修改组件的__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 }