Commit 7f72c8b7 by Jaxon

feat: 添加 Vuex 缓存模块,支持缓存优先策略及接口兜底

1 parent 5ed903b4
...@@ -4,6 +4,7 @@ import Vuex from "vuex"; ...@@ -4,6 +4,7 @@ import Vuex from "vuex";
import ShelfManage from "@/views/goods/shelfManage/store/index.js"; import ShelfManage from "@/views/goods/shelfManage/store/index.js";
import performanceFormStore from "@/views/residentManage/salaryPerformance/performanceScheme/store/performanceFormStore.js"; import performanceFormStore from "@/views/residentManage/salaryPerformance/performanceScheme/store/performanceFormStore.js";
import cacheStore from "./modules/cacheStore";
import d2admin, { storeResets } from "./modules/d2admin"; import d2admin, { storeResets } from "./modules/d2admin";
import FinancialRules from "./modules/FinancialRules"; import FinancialRules from "./modules/FinancialRules";
import goodsInfoData from "./modules/goodsInfoData"; import goodsInfoData from "./modules/goodsInfoData";
...@@ -25,6 +26,7 @@ if (!isProd) { ...@@ -25,6 +26,7 @@ if (!isProd) {
export default new Vuex.Store({ export default new Vuex.Store({
modules: { modules: {
d2admin, d2admin,
cacheStore,
goodsInfoData, goodsInfoData,
FinancialRules, FinancialRules,
PerformanceFormStore: performanceFormStore, PerformanceFormStore: performanceFormStore,
......
# Vuex 缓存模块使用指南
## 1. 模块注册
### 在 `src/store/index.js` 中注册模块
```javascript
import cacheStore from "./modules/cacheStore";
export default new Vuex.Store({
modules: {
cacheStore // 使用命名空间 'cacheStore'
}
});
```
## 2. 组件调用示例
### 基础用法:缓存优先策略
```vue
<template>
<div class="example-container">
<!-- 加载状态 -->
<div v-if="isLoading" class="loading">
数据加载中...
</div>
<!-- 错误显示 -->
<div v-else-if="error" class="error">
{{ error }}
</div>
<!-- 数据显示 -->
<div v-else-if="userData" class="data">
<h3>用户信息</h3>
<p>姓名: {{ userData.name }}</p>
<p>邮箱: {{ userData.email }}</p>
</div>
<!-- 操作按钮 -->
<div class="actions">
<button @click="fetchUserData">
获取用户数据(缓存优先)
</button>
<button @click="refreshUserData">
刷新数据(强制更新)
</button>
<button @click="clearData">
清除缓存
</button>
</div>
</div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
import * as userApi from "@/api/user"; // 导入 API 模块
export default {
name: "UserExample",
data() {
return {
userId: 123 // 示例用户 ID
};
},
computed: {
// 使用 getter 获取缓存数据、加载状态、错误信息
...mapGetters("cacheStore", {
userData: state => state.getCacheData("user_123"),
isLoading: state => state.isLoading("user_123"),
error: state => state.getError("user_123")
})
},
methods: {
...mapActions("cacheStore", ["fetchData", "clearCache"]),
// 缓存优先:第一次调用会从接口获取,第二次调用直接返回缓存
async fetchUserData() {
try {
const data = await this.fetchData({
key: "user_123",
apiFn: userApi.getUserDetailApi,
params: { userId: this.userId }
});
console.log("用户数据:", data);
} catch (error) {
console.error("获取数据失败:", error);
}
},
// 强制刷新:忽略缓存,重新从接口获取
async refreshUserData() {
try {
const data = await this.fetchData({
key: "user_123",
apiFn: userApi.getUserDetailApi,
params: { userId: this.userId },
forceRefresh: true // 强制刷新
});
console.log("最新用户数据:", data);
} catch (error) {
console.error("刷新失败:", error);
}
},
// 清除缓存
clearData() {
this.clearCache("user_123");
}
},
mounted() {
// 组件挂载时自动获取数据
this.fetchUserData();
}
};
</script>
<style scoped>
.loading,
.error,
.data {
padding: 20px;
margin-bottom: 20px;
border-radius: 4px;
}
.loading {
background-color: #e3f2fd;
color: #1976d2;
}
.error {
background-color: #ffebee;
color: #c62828;
}
.data {
background-color: #f3e5f5;
color: #6a1b9a;
}
.actions {
margin-top: 20px;
}
button {
margin-right: 10px;
padding: 8px 16px;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
</style>
```
## 3. 高级用法:带缓存时间限制
```vue
<script>
export default {
methods: {
// 数据缓存 5 分钟(300000 毫秒)后过期
async fetchProductList() {
await this.fetchData({
key: "product_list",
apiFn: productApi.getProductListApi,
params: { category: "electronics" },
cacheTime: 300000 // 5 分钟有效期
});
}
}
};
</script>
```
## 4. API 模块示例
在 `src/api/user.js` 中:
```javascript
import request from "./request";
const path = "dj.api.smartcarlife.";
/**
* 获取用户详情
* @param {object} data - 请求数据
* @param {number} data.userId - 用户 ID
*/
export function getUserDetailApi(data) {
data.method = `${path}user.detail`;
return request(data, "post");
}
/**
* 更新用户信息
*/
export function updateUserApi(data) {
data.method = `${path}user.update`;
return request(data, "post");
}
```
## 5. Vuex 模块核心特性
### ✅ 缓存优先策略
```javascript
// 第一次调用:从接口获取数据并缓存
await this.fetchData({
key: "user_123",
apiFn: userApi.getUserDetailApi,
params: { userId: 123 }
});
// 第二次调用:直接返回缓存数据,不调用接口
await this.fetchData({
key: "user_123",
apiFn: userApi.getUserDetailApi,
params: { userId: 123 }
});
```
### ✅ 避免重复请求
如果在第一个请求还未完成时,又发起了相同的请求,模块会复用之前的 Promise:
```javascript
// 同时发起三个相同的请求
Promise.all([
this.fetchData({ key: "data", apiFn: api1 }),
this.fetchData({ key: "data", apiFn: api1 }),
this.fetchData({ key: "data", apiFn: api1 })
]);
// 只会触发一次接口调用,其他请求复用 Promise
```
### ✅ 完整的状态管理
```javascript
computed: {
...mapGetters('cacheStore', {
data: state => state.getCacheData('key'),
isLoading: state => state.isLoading('key'),
error: state => state.getError('key'),
hasCache: state => state.hasCacheData('key')
})
}
```
### ✅ 灵活的缓存控制
```javascript
// 清除指定缓存
this.$store.dispatch("cacheStore/clearCache", "user_123");
// 清除所有缓存
this.$store.dispatch("cacheStore/clearAllCache");
// 手动更新缓存
this.$store.dispatch("cacheStore/updateCache", {
key: "user_123",
value: newData
});
```
## 6. 在路由守卫中预加载数据
```javascript
// src/router/index.js
router.beforeEach((to, from, next) => {
if (to.meta.requiresData) {
store.dispatch('cacheStore/fetchData', {
key: to.meta.dataKey,
apiFn: to.meta.dataApi,
params: to.params
}).then(() => {
next()
}).catch(() => {
next(false)
})
} else {
next()
}
})
// 路由定义
{
path: '/user/:id',
component: UserDetail,
meta: {
requiresData: true,
dataKey: 'user_detail',
dataApi: userApi.getUserDetailApi
}
}
```
## 7. TypeScript 支持(可选)
如果项目使用 TypeScript,可以定义接口:
```typescript
interface FetchDataOptions {
key: string
apiFn: (params: any) => Promise<any>
params?: Record<string, any>
forceRefresh?: boolean
cacheTime?: number
}
interface CacheState {
cache: Record<string, any>
loading: Record<string, boolean>
errors: Record<string, string | null>
requestMap: Record<string, Promise<any>>
}
```
## 总结
| 功能 | 说明 |
|------|------|
| 缓存优先 | 优先检查 state 中的缓存,无缓存则调用接口 |
| 接口兜底 | 缓存无效时自动调用接口获取最新数据 |
| 避免重复 | 相同请求进行中时复用 Promise,避免重复调用 |
| 时间限制 | 支持设置缓存有效期,过期自动更新 |
| 完整状态 | 加载状态、错误信息、缓存数据全方位管理 |
| 命名空间 | 开启 namespaced,防止状态冲突 |
| 响应式 | 通过 mutation 更新,保证视图同步更新 |
/**
* Vuex 缓存模块 - 支持缓存优先、接口兜底
* 特性:
* 1. 缓存优先策略:state中有有效值则直接返回,无则调用接口
* 2. 支持自定义参数:接口函数可接收 params 参数
* 3. 避免重复请求:使用 requestMap 跟踪请求中的 Promise
* 4. 完整的加载/错误状态管理
* 5. 开启命名空间防止状态冲突
*/
export default {
namespaced: true,
state: {
// 缓存数据存储对象,key为缓存键名,value为缓存数据
cache: {},
// 加载状态映射,key为缓存键名,value为 boolean
loading: {},
// 错误信息映射,key为缓存键名,value为错误信息字符串
errors: {},
// 正在进行的请求 Promise 映射,用于避免重复请求
// key为缓存键名,value为 Promise 对象
requestMap: {},
},
mutations: {
/**
* 设置缓存数据
* @param {string} key - 缓存键名
* @param {*} value - 缓存数据值
*/
SET_CACHE(state, { key, value }) {
state.cache[key] = value;
},
/**
* 设置加载状态
* @param {string} key - 缓存键名
* @param {boolean} loading - 加载状态
*/
SET_LOADING(state, { key, loading }) {
state.loading[key] = loading;
},
/**
* 设置错误信息
* @param {string} key - 缓存键名
* @param {string} error - 错误信息,null 表示清除错误
*/
SET_ERROR(state, { key, error }) {
state.errors[key] = error;
},
/**
* 设置请求 Promise(用于防止重复请求)
* @param {string} key - 缓存键名
* @param {Promise} promise - Promise 对象或 null
*/
SET_REQUEST(state, { key, promise }) {
if (promise) {
state.requestMap[key] = promise;
} else {
delete state.requestMap[key];
}
},
/**
* 清除指定键的所有数据
* @param {string} key - 缓存键名
*/
CLEAR_CACHE(state, key) {
delete state.cache[key];
delete state.loading[key];
delete state.errors[key];
delete state.requestMap[key];
},
/**
* 清空所有缓存数据
*/
CLEAR_ALL_CACHE(state) {
state.cache = {};
state.loading = {};
state.errors = {};
state.requestMap = {};
},
},
actions: {
/**
* 获取缓存数据或调用接口获取
* 核心方法:实现缓存优先、接口兜底的逻辑
*
* @param {object} context - Vuex action context
* @param {object} options - 配置选项
* @param {string} options.key - 缓存键名(必填)
* @param {Function} options.apiFn - 接口函数(必填),返回 Promise
* @param {object} options.params - 接口参数(可选)
* @param {boolean} options.forceRefresh - 是否强制刷新,忽略缓存(可选,默认 false)
* @param {number} options.cacheTime - 缓存有效期(毫秒),0 表示永久有效(可选,默认 0)
* @returns {Promise} 返回缓存数据或接口响应数据
*/
async fetchData({ state, commit }, options) {
const { key, apiFn, params = {}, forceRefresh = false, cacheTime = 0 } = options;
if (!key || !apiFn) {
throw new Error("fetchData 方法必须提供 key 和 apiFn 参数");
}
// 1. 检查是否有正在进行的请求,有则直接返回 Promise (避免重复请求)
if (state.requestMap[key]) {
return state.requestMap[key];
}
// 2. 缓存优先策略:检查是否有有效缓存(非强制刷新)
if (!forceRefresh && state.cache[key] !== undefined) {
// 如果设置了缓存时间限制,需要检查缓存是否过期
if (cacheTime === 0 || (state.cache[key]._timestamp && Date.now() - state.cache[key]._timestamp < cacheTime)) {
return state.cache[key];
}
}
// 3. 无有效缓存,调用接口获取数据
commit("SET_LOADING", { key, loading: true });
commit("SET_ERROR", { key, error: null });
const promise = apiFn(params).then((response) => {
// 接口成功响应
const data = response.data || response;
// 如果设置了缓存时间,记录时间戳
const cacheData = cacheTime > 0
? Object.assign({}, data, { _timestamp: Date.now() })
: data;
// 存储到 state,保证响应式
commit("SET_CACHE", { key, value: cacheData });
commit("SET_ERROR", { key, error: null });
commit("SET_LOADING", { key, loading: false });
commit("SET_REQUEST", { key, promise: null });
return cacheData;
}).catch((error) => {
// 接口调用失败
const errorMsg = error.message || "数据获取失败";
commit("SET_ERROR", { key, error: errorMsg });
commit("SET_LOADING", { key, loading: false });
commit("SET_REQUEST", { key, promise: null });
console.error(`[cacheStore] 接口请求失败 [${key}]:`, error);
throw error;
});
// 保存正在进行的请求
commit("SET_REQUEST", { key, promise });
return promise;
},
/**
* 手动更新缓存数据
* @param {object} context - Vuex action context
* @param {object} options - 配置选项
* @param {string} options.key - 缓存键名
* @param {*} options.value - 新的缓存值
*/
updateCache({ commit }, { key, value }) {
commit("SET_CACHE", { key, value });
},
/**
* 清除指定缓存
* @param {object} context - Vuex action context
* @param {string} key - 缓存键名
*/
clearCache({ commit }, key) {
commit("CLEAR_CACHE", key);
},
/**
* 清空所有缓存
* @param {object} context - Vuex action context
*/
clearAllCache({ commit }) {
commit("CLEAR_ALL_CACHE");
},
},
getters: {
/**
* 获取指定键的缓存数据
*/
getCacheData: state => (key) => {
return state.cache[key];
},
/**
* 获取指定键的加载状态
*/
isLoading: state => (key) => {
return state.loading[key] || false;
},
/**
* 获取指定键的错误信息
*/
getError: state => (key) => {
return state.errors[key] || null;
},
/**
* 检查指定键是否有有效缓存
*/
hasCacheData: state => (key) => {
return state.cache[key] !== undefined;
},
},
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!