避免頻繁向后端發送請求,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>