公共方法封装.js
// axios 取消请求
let [timer, pedding] = [null, {}];
export const __catchAPI = (path, callback, config) => {
if (typeof callback === 'function') {
// 请求接口的时候 加入pendding
const row = {
cancelXhr: true,
config,
data: {
timestamp: new Date(),
path,
error: 'cancel_xhr',
message: '取消请求接口'
}
};
pedding[path] = () => callback(row);
// 避免内存扩大 10秒后 清除pending
clearTimeout(timer);
timer = setTimeout(() => (pedding = {}), 10000);
} else {
// 没有callback 就执行停止请求操作
const reg = new RegExp(`${path}$`);
const k = Object.keys(pedding).find(u => reg.test(u));
if (!k) return;
pedding[k]();
delete pedding[k];
}
};
二次封装axios
import __catchAPI from '公共方法封装.js';
const Cancel = axios.CancelToken;
service.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json';
if (!config.headers.token && store.getters.token) {
config.headers['token'] = store.getters.token;
}
// 配置全局加载
if (config.loading) {
showFullScreenLoading();
}
config.cancelToken = new Cancel(cb => __catchAPI(config.url, cb, config));
return config;
});