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 持久化存储
-
适用场景:低频变更的核心数据(如配置信息)
-
实现方案 :
javascriptfunction 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;
}
}
四、组合策略实施方案
-
优先级设计:
- 内存缓存 > 本地缓存 > 网络请求
- 组件缓存优先于重新渲染
-
缓存更新机制:
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); }); -
缓存监控方案:
- 添加缓存命中率统计
- 设置缓存体积预警机制
- 开发环境添加缓存调试工具
五、注意事项
-
敏感数据处理:
- 避免在 localStorage 存储敏感信息
- 内存缓存需考虑页面刷新失效
-
内存管理:
- 设置合理的缓存过期时间
- 实现 LRU (最近最少使用) 淘汰策略
-
版本兼容:
javascript// 缓存版本控制 const CACHE_VERSION = 'v1.2'; function getCacheKey(url) { return `${CACHE_VERSION}_${url}`; }
此组合方案通过三级缓存体系(接口→组件→路由),在保证数据实时性的同时减少网络请求和渲染开销,适用于中大型 Vue 应用。具体实施时需根据业务场景调整缓存策略参数。