USAGE_EXAMPLE.md
6.92 KB
Vuex 缓存模块使用指南
1. 模块注册
在 src/store/index.js 中注册模块
import cacheStore from "./modules/cacheStore";
export default new Vuex.Store({
modules: {
cacheStore // 使用命名空间 'cacheStore'
}
});
2. 组件调用示例
基础用法:缓存优先策略
<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. 高级用法:带缓存时间限制
<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 中:
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 模块核心特性
✅ 缓存优先策略
// 第一次调用:从接口获取数据并缓存
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:
// 同时发起三个相同的请求
Promise.all([
this.fetchData({ key: "data", apiFn: api1 }),
this.fetchData({ key: "data", apiFn: api1 }),
this.fetchData({ key: "data", apiFn: api1 })
]);
// 只会触发一次接口调用,其他请求复用 Promise
✅ 完整的状态管理
computed: {
...mapGetters('cacheStore', {
data: state => state.getCacheData('key'),
isLoading: state => state.isLoading('key'),
error: state => state.getError('key'),
hasCache: state => state.hasCacheData('key')
})
}
✅ 灵活的缓存控制
// 清除指定缓存
this.$store.dispatch("cacheStore/clearCache", "user_123");
// 清除所有缓存
this.$store.dispatch("cacheStore/clearAllCache");
// 手动更新缓存
this.$store.dispatch("cacheStore/updateCache", {
key: "user_123",
value: newData
});
6. 在路由守卫中预加载数据
// 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,可以定义接口:
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 更新,保证视图同步更新 |