看官方仓库源码,缓存的Key是用组件名称来做的:github地址
原理就是修改组件的__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
}

