vue3实现跨页面缓存

避免频繁向后端发送请求,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 && globalCachecacheKey) {

myStores.value = globalCachecacheKey.data;

totalCount.value = globalCachecacheKey.total_count;

return;

}

让缓存从globalCache里面取,

完整代码:

javascript 复制代码
<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>
相关推荐
小七-七牛开发者7 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
ofoxcoding14 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen14 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans14 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时14 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚14 天前
Linux——Redis
数据库·redis·缓存
小挪号底迪滴14 天前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存
闪电悠米14 天前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Saniffer_SH15 天前
【高清视频】Gen6 服务器还没到,Gen6 SSD 怎么测?Emily 现场演示三种测试环境
人工智能·驱动开发·测试工具·缓存·fpga开发·计算机外设·压力测试