不同的路由共用一个组件component,并用keepAlive实现不同的页面缓存
实现的效果:十几个页面使用的路由是同一个,但是从A页面到B页面或者其他页面的时候,希望之前输入的数据还存在。
keep-alive可以接收3个属性做为参数进行匹配对应的组件进行缓存:
- include 字符串或正则表达式。只有名称匹配的组件会被缓存
- exclude字符串或正则表达式。任何名称匹配的组件都不会被缓存
- max 数字。最多可以缓存多少组件实例(如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间。)
它会根据组件的 name 选项进行匹配,所以组件如果想要条件性地被 KeepAlive 缓存,就必须显式声明一个 name 选项。
虽然使用了keep-alive,但是使用共同组件的页面,没有进行缓存,因为他们的name是不一致,所以不能缓存,最初的写法是这样的。
<keep-alive v-if="openCache" :include="getCaches">
<component :is="Component" :key="route.fullPath" />
</keep-alive>
因为要实现效果,所以根据整理到的一些资料和其他的博客那里看到的,换了一种写法
<keep-alive v-if="openCache" :include="getCaches">
<component :is="wrap(route.name, Component)" :key="route.fullPath" />
</keep-alive>
给component重新命名,很多页面涉及到多个路由调用同一个组件,只要确保路由名称唯一就行。
<script lang="ts" setup>
const cacheMap = new Map();
const wrap = (name, component) => {
let cache;
const cacheName = name;
if (cacheMap.has(cacheName)) {
cache= cacheMap.get(cacheName);
} else {
cache = {
name: cacheName,
render() {
return h('div', { className: 'cache-page-wrapper' }, component);
},
};
cacheMap.set(cacheName, cache);
}
return h(cache);
};
</script>
这样就可以实现多页面使用同一个路由,进行缓存。