第七阶段:企业级项目实战核心能力(118天)Vue项目缓存策略:接口缓存(内存+本地)+ 组件缓存+路由缓存组合方案

Vue项目缓存策略组合方案

一、接口缓存策略

1. 内存缓存(短期缓存)

  • 实现原理:使用内存存储高频访问数据

  • 适用场景:实时性要求高但更新频率低的数据(如用户信息)

  • 实现方案

    javascript 复制代码
    // 创建内存缓存对象
    const apiCache = new Map();
    
    async function fetchWithCache(url) {
      if (apiCache.has(url)) {
        return Promise.resolve(apiCache.get(url));
      }
      const res = await axios.get(url);
      apiCache.set(url, res.data);  // 设置10分钟有效期
      setTimeout(() => apiCache.delete(url), 600000);
      return res.data;
    }

2. 本地缓存(长期存储)

  • 实现原理:使用 localStorage/sessionStorage 持久化存储

  • 适用场景:低频变更的核心数据(如配置信息)

  • 实现方案

    javascript 复制代码
    function getLocalData(key) {
      const cached = localStorage.getItem(key);
      if (cached) {
        const { data, expire } = JSON.parse(cached);
        if (Date.now() < expire) return data;
      }
      return null;
    }
    
    function setLocalData(key, data, ttl = 86400000) {
      const store = {
        data,
        expire: Date.now() + ttl
      };
      localStorage.setItem(key, JSON.stringify(store));
    }
二、组件缓存策略

1. 动态组件缓存

vue 复制代码
<template>
  <keep-alive :include="cachedComponents">
    <component :is="currentComponent"/>
  </keep-alive>
</template>

<script>
export default {
  data() {
    return {
      cachedComponents: ['UserProfile', 'DashboardWidget'],
      currentComponent: 'UserProfile'
    }
  }
}
</script>

2. 条件缓存策略

  • 使用 v-if 控制缓存激活状态
  • 通过 max 属性限制最大缓存实例数(Vue 2.5+)
vue 复制代码
<keep-alive :max="5">
  <router-view v-if="$route.meta.keepAlive"/>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"/>
三、路由缓存策略

1. 路由元信息配置

javascript 复制代码
// router.js
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: {
      keepAlive: true,  // 启用缓存
      scrollPos: true   // 记录滚动位置
    }
  }
]

2. 滚动行为控制

javascript 复制代码
// router.js
const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition && to.meta.scrollPos) {
      return savedPosition;
    }
    return { x: 0, y: 0 };
  }
});

3. 路由生命周期钩子

javascript 复制代码
// 在路由组件内
beforeRouteLeave(to, from, next) {
  if (from.meta.keepAlive) {
    // 保存组件状态
    this.$store.commit('SAVE_COMPONENT_STATE', this.internalState);
  }
  next();
},
activated() {
  // 恢复缓存状态
  if (this.$store.state.componentState) {
    this.internalState = this.$store.state.componentState;
  }
}
四、组合策略实施方案
  1. 优先级设计

    • 内存缓存 > 本地缓存 > 网络请求
    • 组件缓存优先于重新渲染
  2. 缓存更新机制

    javascript 复制代码
    // 主动更新策略
    function refreshCache(key) {
      if (apiCache.has(key)) apiCache.delete(key);
      if (localStorage.getItem(key)) localStorage.removeItem(key);
    }
    
    // 事件驱动更新
    EventBus.$on('data-update', (payload) => {
      refreshCache(payload.cacheKey);
    });
  3. 缓存监控方案

    • 添加缓存命中率统计
    • 设置缓存体积预警机制
    • 开发环境添加缓存调试工具
五、注意事项
  1. 敏感数据处理

    • 避免在 localStorage 存储敏感信息
    • 内存缓存需考虑页面刷新失效
  2. 内存管理

    • 设置合理的缓存过期时间
    • 实现 LRU (最近最少使用) 淘汰策略
  3. 版本兼容

    javascript 复制代码
    // 缓存版本控制
    const CACHE_VERSION = 'v1.2';
    function getCacheKey(url) {
      return `${CACHE_VERSION}_${url}`;
    }

此组合方案通过三级缓存体系(接口→组件→路由),在保证数据实时性的同时减少网络请求和渲染开销,适用于中大型 Vue 应用。具体实施时需根据业务场景调整缓存策略参数。

相关推荐
happymaker06262 小时前
Spring学习日记——DAY04(复杂对象创建,AOP静态代理)
java·开发语言·spring
jasnet_u3 小时前
SpringMVC 请求处理深度解析:从 DispatcherServlet 到视图渲染
spring·springmvc·springboot
接着奏乐接着舞4 小时前
springcloud Sentinel
spring·spring cloud·sentinel
w_t_y_y4 小时前
VUE组件配置项(零)概述
前端·javascript·vue.js
水云桐程序员4 小时前
Web应用的分类
前端·javascript·vue.js·react.js·webkit
鱼鳞_4 小时前
苍穹外卖-Day01(开发环境搭建)
java·spring boot·spring·maven
Csvn4 小时前
JS 技巧:设计模式(上)
前端·vue.js
用户398346161204 小时前
Go-Spring 实战第 4 课 —— 配置校验:使用 expr 标签拦截非法配置
spring·go