调整页面跳转后缓存问题

This commit is contained in:
Ledo 2025-08-19 14:47:08 +08:00
parent 139474bec6
commit 79a62df340
3 changed files with 125 additions and 6 deletions

View File

@ -0,0 +1,100 @@
import { pa } from 'element-plus/es/locale';
import { reactive } from 'vue';
import type { RouteLocationNormalized } from 'vue-router';
export type QueryParams = {
pageNo: number;
pageSize: number;
planNo?: string;
projectCode?: string;
customerName?: string;
projectName?: string;
businessManName?: string;
businessLine?: string;
property?: string;
projectOwner?: string;
status?: string;
[key: string]: any;
};
type CachedParams = {
queryParams: QueryParams;
timestamp: number;
};
const DEFAULT_EXPIRE_HOURS = 24;
const ROUTE_PARAMS_CACHE_KEY = 'route_params_cache_v2'; // 加个版本号避免冲突
// 生成唯一缓存键(包含路径和查询参数)
const getCacheKey = (route: RouteLocationNormalized) => {
return `${route.path}?${JSON.stringify(route.query)}`;
};
// 初始化缓存(从 sessionStorage 加载)
const saveCache = (cache: Map<string, CachedParams>) => {
const serializable = Object.fromEntries(
Array.from(cache.entries()).map(([key, value]) => [
key,
{
queryParams: value.queryParams,
timestamp: value.timestamp,
},
])
);
localStorage.setItem(ROUTE_PARAMS_CACHE_KEY, JSON.stringify(serializable));
};
const initCache = (): Map<string, CachedParams> => {
const cached = localStorage.getItem(ROUTE_PARAMS_CACHE_KEY);
if (!cached) return new Map();
try {
const parsed = JSON.parse(cached);
return new Map(
Object.entries(parsed).map(([key, value]: [string, any]) => [
key,
{
queryParams: value.queryParams,
timestamp: value.timestamp,
},
])
);
} catch (e) {
console.error('Failed to parse route params cache:', e);
return new Map();
}
};
// 导出默认实例
const routeParamsCache = {
cache: initCache(),
set(route: RouteLocationNormalized, params: QueryParams) {
console.log('调用了')
const path = getCacheKey(route); // 使用路由对象生成唯一键
const cachedParams: CachedParams = {
queryParams: JSON.parse(JSON.stringify(params)),
timestamp: Date.now(),
};
this.cache.set(path, cachedParams);
saveCache(this.cache);
},
get(route: RouteLocationNormalized) {
const path = getCacheKey(route);
return this.cache.get(path)?.queryParams; // 简化返回
},
cleanExpired(expireHours = DEFAULT_EXPIRE_HOURS) {
const now = Date.now();
const expired = Array.from(this.cache.entries()).filter(
([_, { timestamp }]) => now - timestamp > expireHours * 60 * 60 * 1000
);
expired.forEach(([key]) => this.cache.delete(key));
saveCache(this.cache);
},
clear() {
this.cache.clear();
saveCache(this.cache);
},
};
export default routeParamsCache;

View File

@ -2,6 +2,7 @@ import type { RouteLocationNormalized, Router, RouteRecordNormalized } from 'vue
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { isUrl } from '@/utils/is'
import { cloneDeep, omit } from 'lodash-es'
import { KeepAlive } from 'vue'
const modules = import.meta.glob('../views/**/*.{vue,tsx}')
/**
@ -68,7 +69,7 @@ export const generateRoute = (routes: AppCustomRouteRecordRaw[]): AppRouteRecord
title: route.name,
icon: route.icon,
hidden: !route.visible,
noCache: !route.keepAlive,
keepAlive:route.keepAlive,
alwaysShow:
route.children &&
(route.alwaysShow !== undefined ? route.alwaysShow : true)
@ -115,7 +116,8 @@ export const generateRoute = (routes: AppCustomRouteRecordRaw[]): AppRouteRecord
path: '/external-link',
component: Layout,
meta: {
name: route.name
name: route.name,
keepAlive:true
},
children: [data]
} as AppRouteRecordRaw
@ -161,6 +163,7 @@ export const pathResolve = (parentPath: string, path: string) => {
// 路由降级
export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
const modules: AppRouteRecordRaw[] = cloneDeep(routes)
console.log(routes)
for (let index = 0; index < modules.length; index++) {
const route = modules[index]
if (!isMultipleRoute(route)) {
@ -198,6 +201,7 @@ const promoteRouteLevel = (route: AppRouteRecordRaw) => {
})
const routes = router.getRoutes()
console.log(routes)
addToChildren(routes, route.children || [], route)
router = null

View File

@ -180,7 +180,7 @@ import Print from './productionPrint.vue' // 引入打印弹框
import A3sonPrint from './A3sonPrint.vue' // A3
import * as UserApi from '@/api/system/user'
import {disposeCoordSysRecordIfNeeded} from "echarts/types/src/component/dataZoom/roams";
import routeParamsCache from '@/utils/routeParamsCache';
defineOptions({ name: 'Plan' })
const message = useMessage() //
@ -303,12 +303,27 @@ const handleExport = async () => {
}
const userInit = ref()
/** 初始化 **/
const route = useRoute()
onMounted(async () => {
//
userInit.value = await UserApi.getSimpleUserList()
let params = routeParamsCache.get(route.path);
if (params ) {
Object.assign(queryParams, params);
}
await getList()
})
});
onBeforeUnmount(() => {
const plainParams = JSON.parse(JSON.stringify(queryParams));
routeParamsCache.set(route.path, plainParams);
});
window.addEventListener('beforeunload', () => {
const plainParams = JSON.parse(JSON.stringify(queryParams));
routeParamsCache.set(route.path, plainParams);
});
</script>
<style scoped>
.el-dropdown-link {