前台加载后台传输数据时,想要有一个加载过程中遮罩层的效果如何实现
自己封装一个axios拦截器,在前台向后台发出请求时,在请求拦截时调用Open()打开遮罩层,其他时间都关闭,引入element-ui组件库中的Loading,Message,创建loading实例,添加open和close方法实现打开和关闭遮罩层,上代码。
下面展示一些 内联代码片
。
import axios from 'axios';
import { Loading, Message } from 'element-ui';
// 封装axios
const request = axios.create({
// baseURL:'/',
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
});
const loading = {
loadingInstance: null,
// 打开遮罩层
open: function () {
if (this.loadingInstance === null) {
this.loadingInstance = Loading.service({
text: "玩命加载中...",
target: ".main", //你要添加遮罩层的模块
background: "rgba(0,0,0,0.5)"
})
}
},
// 关闭遮罩层
close: function () {
if (this.loadingInstance !== null) {
this.loadingInstance.close();
}
this.loadingInstance = null;
}
}
// 添加一个请求拦截器
request.interceptors.request.use(function (config) {
// 请求拦截
loading.open();
return config;
}, function (error) {
// 抛出异常
loading.close();
return Promise.reject(error);
});
// 添加一个响应拦截器
request.interceptors.response.use(function (response) {
// 响应拦截
const resp = response.data;
if (resp.code != 2000) {
Message({
message: resp.message,
type: "warning",
duration: 5 * 1000,
})
}
loading.close();
return response;
}, function (error) {
// 抛出异常
Message({
message: resp.error,
type: "error",
duration: 5 * 1000, //message提示框停留时间
})
loading.close();
return Promise.reject(error);
});
export default request;;