在 vue 开发中,我们偶尔会遇到相同组件多次调用一个请求的问题,即使添加了缓存,但在第一次调用时也会出现这类问题,这种问题的根源往往是由于第一个组件发起的请求没有返回数据,第二个组件没有在缓存中获取到数据而重新发起请求。
解决这种问题我们往往可以分两种:
具体使用见下方代码:
在axios中,添加
const cacheMap = {};
响应拦截添加
try {
// 删除缓存
const baseApi = res.config.url.replace(service.defaults.baseURL, "");
let api;
if (res.config.method === 'get') {
api = baseApi + JSON.stringify(res.config.params);
} else {
api = baseApi + JSON.stringify(res.config.data);
}
if (cacheMap.hasOwnProperty(api)) {
delete cacheMap[api];
}
} catch (err) {
}
创建两个请求方法
/**
* Get缓存请求
*/
export const cacheGet = async (api, params) => {
if (api.indexOf("/") !== 0) {
api = "/" + api;
}
const key = api + JSON.stringify(params);
if (!cacheMap.hasOwnProperty(key)) {
cacheMap[key] = service({
url: api,
method: 'get',
params
});
}
return cacheMap[key];
}
/**
* Post缓存请求
*/
export const cachePost = async (api, data) => {
if (api.indexOf("/") !== 0) {
api = "/" + api;
}
const key = api + JSON.stringify(data);
if (cacheMap.hasOwnProperty(key)) {
cacheMap[key] = service({
url: api,
method: 'post',
data
});
}
return cacheMap[key];
}