loading加载
1.按需导入 ElementUI 组件 Loading
2.加载数据时, 打开和关闭 对象 (注意: loadingInstance 实例采用单例模式创建,防止响应异常时频繁切换路由时加载动效重复创建)
3.请求拦截器中打开加载效果, 响应拦截器和异常中关闭加载效果.
统一异常处理
在响应拦截器中设置
加载和统一异常处理的完整代码:
import axios from 'axios';
import { Loading, Message } from 'element-ui';
const loading = {
loadingInstance: null, //loading实例
// 打开加载
open: function () {
// 创建实例,而且会加载窗口
if (this.loadingInstance === null) {
//采用单例
this.loadingInstance = Loading.service({
target: '.main',
text: '拼命加载中'
});
}
},
// 关闭加载
close: function () {
// 不为空时,则关闭加载窗口
if (this.loadingInstance !== null) {
this.loadingInstance.close();
}
this.loadingInstance = null;
}
};
const request = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000 //请求超时,5000毫秒
});
// 请求拦截器
request.interceptors.request.use(
(config) => {
// 请求拦截
// 打开加载窗口
loading.open();
return config;
},
(error) => {
// 关闭加载窗口
loading.close();
return Promise.reject(error);
}
);
// 响应拦截器
request.interceptors.response.use(
(response) => {
// 响应拦截
// 关闭加载窗口
loading.close();
const resp = response.data;
// 后台正常响应的状态,如果不是2000,说明后台处理有问题
if (resp.code !== 2000) {
Message({
message: resp.message || '系统异常',
type: 'warning',
duration: 5 * 1000
});
}
return response;
},
(error) => {
// 关闭加载窗口
loading.close();
//断网会出现这样的错误 |请求路径错误
// 当请求接口出错时, 进行弹出错误提示, 如 404, 500, 请求超时
console.log('response error', error.response.status)
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default request;