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) => { 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 => { 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;