封装一个loading,每次加载的时候动态显示加载框;且自动刷新不会影响弹框上传文件的弹框
思路:给config添加headers ,其中自定义一个变量showLoading
import axios from 'axios';
import { getStorage } from './storage';
import { showLoading, hideLoading } from './loading';
import { Message } from 'element-ui';
import qs from 'qs';
import merge from 'lodash/merge';
// eslint-disable-next-line spellcheck/spell-checker
const project = process.env.VUE_APP_PROJECT || 'xxx'; // 默认xxx
class AxiosFetch {
constructor() {
axios.interceptors.request.use(params => {
if (params.headers.showLoading) {
showLoading();
}
// 处理请求数据,如添加Header信息等,
const config = {
...params,
url: `${params.url}`,
headers: {
...params.headers,
'Access-Token': getStorage(project + 'token'),
},
};
if (config.method === 'get') {
config.paramsSerializer = function (params) {
return qs.stringify(params, { arrayFormat: 'repeat' });
};
}
return config;
});
axios.interceptors.response.use(
response => {
if (response.config.headers.showLoading) {
hideLoading();
}
// 处理返回数据
return response.data;
},
error => {
if (error.config.headers.showLoading) {
hideLoading();
}
if (error.response.data && error.response.data.message) {
Message.error({
message: error.response.data.message,
});
}
if (error.response.status === 401 || error.response.status === 40003) {
document.location.href = '/';
}
return Promise.reject(error);
},
);
}
private getConfig(config, loading) {
// merge 并集.给config添加headers ,其中自定义一个变量showLoading
return merge({}, config, { headers: { showLoading: loading } });
}
public get(url: string, config: object = {}, loading = true): Promise<any> {
// this.getConfig(config, loading) 就是请求拦截器的params
return axios.get(url, this.getConfig(config, loading));
}
public post(url: string, data: any = {}, config: object = {}, loading = true): Promise<any> {
return axios.post(url, data, this.getConfig(config, loading));
}
public put(url: string, data: any, config: object = {}, loading = true): Promise<any> {
return axios.put(url, data, this.getConfig(config, loading));
}
public delete(url: string, config: object = {}, loading = true): Promise<any> {
return axios.delete(url, this.getConfig(config, loading));
}
}
const Fetch = new AxiosFetch();
export default Fetch;