避免频繁向后端发送请求,vue3中,可以用缓存机制,为了实现跨页面缓存,可以把缓存放到localsotrage里面
关键代码:
const globalCache = JSON.parse(localStorage.getItem('globalCache')) || {};
然后加一个forceRefresh关键字,
const fetchData = async (forceRefresh = false) => {
const cacheKey = `${userId.value}-${currentPage.value}-${pageSize.value}`;
if (!forceRefresh && globalCache[cacheKey]) {
myStores.value = globalCache[cacheKey].data;
totalCount.value = globalCache[cacheKey].total_count;
return;
}
让缓存从globalCache里面取,
完整代码:
<template>
<!-- 清空缓存按钮 -->
<router-link to="/home" custom v-slot="{ navigate }">
<van-button
type="default"
@click="
// 清空全局缓存对象的所有属性
Object.keys(globalCache).forEach(key => delete globalCache[key]);
// 强制刷新数据(跳过缓存)
fetchData(true);
navigate();
"
size="small"
>
打卡店铺
</van-button>
</router-link>
</template>
<script setup>
// 缓存系统核心实现
// ------------------------------------------------------------------
// 初始化全局缓存:从 localStorage 加载已有缓存或创建空对象
const globalCache = JSON.parse(localStorage.getItem('globalCache')) || {};
// 缓存更新方法
const updateCache = (cacheKey, data) => {
// 将新数据存入缓存对象
globalCache[cacheKey] = data;
// 同步更新到 localStorage 持久化存储
localStorage.setItem('globalCache', JSON.stringify(globalCache));
};
// 清空缓存方法
const clearCache = () => {
// 遍历删除缓存对象所有属性
Object.keys(globalCache).forEach(key => delete globalCache[key]);
// 清除 localStorage 中的持久化存储
localStorage.removeItem('globalCache');
};
// 数据获取逻辑(带缓存机制)
const fetchData = async (forceRefresh = false) => {
// 生成当前请求的缓存键(用户ID+分页参数)
const cacheKey = `${userId.value}-${currentPage.value}-${pageSize.value}`;
// 缓存命中逻辑(当非强制刷新且存在有效缓存时)
if (!forceRefresh && globalCache[cacheKey]) {
// 从缓存读取数据
myStores.value = globalCache[cacheKey].data;
totalCount.value = globalCache[cacheKey].total_count;
return;
}
// 无有效缓存时发起网络请求
const response = await axios.get(`${baseURL}/query_store/${userId.value}?page=${currentPage.value}&pageSize=${pageSize.value}`);
// 更新响应数据到缓存系统
updateCache(cacheKey, {
data: response.data.data,
total_count: response.data.total_count,
});
};
// 路由导航守卫(控制页面离开时的缓存清理)
onBeforeRouteLeave((to, from, next) => {
// 仅当跳转到信息填报页面时保留缓存
if (to.name === 'informationFill') {
next();
} else {
// 其他路由跳转时清空缓存
clearCache();
next();
}
});
</script>