1:使用场景
从列表页跳转至不同的详情页面,对这些详情页面分别进行缓存
2:核心代码
2.1: 配置路由文件
在路由文件里对需要进行缓存的路由对象添加meta 属性
// 需要缓存的详情页面路由
{
name: detail,
path: '/myRouter/detail', // 路径
component: () => import('../views/abc/detail.vue'),
meta: {
keepAlive: true, // 是否被缓存
},
},
2.2: app页面增加缓存逻辑
<template>
<el-config-provider :locale="locale">
<!-- 有条件的进行缓存 -->
<transition mode="out-in" name="fade">
<router-view v-slot="{ Component }">
<keep-alive :include="includeList">
<component :is="wrap(route?.name , route.query, Component)" :key="route.fullPath" />
</keep-alive>
</router-view>
</transition>
</el-config-provider>
</template>
wrap 方法
javascript
const wrapperMap = new Map();
const wrap = (name:any, query:any, component:any) => {
let wrapper;
let wrapperName;
if(query.catchName){
wrapperName = name + '-' + query.catchName;
}else {
wrapperName = name;
}
if (wrapperMap.has(wrapperName)) {
wrapper = wrapperMap.get(wrapperName);
} else {
wrapper = {
name: wrapperName,
render() {
return h('div', { className: 'vaf-page-wrapper' }, component);
},
};
wrapperMap.set(wrapperName, wrapper);
}
return h(wrapper);
};
watch 监听对于route.query 是否存在catchName 参数的路由分别进行缓存
javascript
// 监听路由,判断页面是否需要缓存
watch(
() => route,
(newVal: any, oldVal) => {
if (newVal.query?.catchName) {
if (newVal.meta.keepAlive && !state.includeList.includes(newVal.name + '-' + newVal.query?.catchName)) {
state.includeList.push(newVal.name + '-' + newVal.query?.catchName);
}
} else if (newVal.meta.keepAlive && !state.includeList.includes(newVal.name)) {
state.includeList.push(newVal.name);
}
},
{
deep: true, // 开启深度监听
},
);
2.3: 在列表页面的查看点击方法中配置路由添加query 传参 catchName
注:上面为核心代码逻辑,需要根据实际情况进行调整。