需求
1.后台数据在800ms返回,不添加loading遮罩层
2.后台数据超过在800ms未返回,添加loading遮罩层
代码效果如下
前端代码
import axios from "axios";
import { Loading } from 'element-ui';
let loadingInstance = null;//蒙版实例
let timer = null;//定时器
// 创建axios实例
const instance = axios.create({ timeout: 1000 * 60 });
/**
* 设置默认请求头
*/
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
//添加默认请求路径
if (process.env.NODE_ENV == 'development') {
instance.defaults.baseURL = '/myapi';
}
else if (process.env.NODE_ENV == 'production') {
instance.defaults.baseURL = "";
}
/**
* 请求拦截器
* 1. 每次请求前,添加蒙板
*/
instance.interceptors.request.use(
config=> {
// 添加遮罩层
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
//如果存在则关闭
if (loadingInstance !== null) {
loadingInstance.close();
}
loadingInstance = Loading.service({
lock: true,
text: '努力加载中!',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.3)'
});
}, 800);
return config;
},
error=>Promise.error(error)
)
/**
* 响应拦截器
*
*/
instance.interceptors.response.use(
// 请求成功
res => {
//如果请求返回快的话,就不需要loading
// 清除定时器
clearTimeout(timer);
timer = null;
// 请求返回后,关闭loading
if (loadingInstance !== null) {
loadingInstance.close();
}
if (res.status === 200) {
return Promise.resolve(res.data);
} else {
return Promise.reject(res.data);
}
},
error=> {
//如果请求返回快的话,就不需要loading
// 清除定时器
clearTimeout(timer);
timer = null;
// 请求返回后,关闭loading
if (loadingInstance !== null) {
loadingInstance.close();
}
return Promise.reject(error);
}
)
export default instance;
后台代码
/* GET users listing. */
router.get('/getName1', function(req, res, next) {
res.json({
name: "喝鸡汤"
});
});
router.get('/getName2', function(req, res, next) {
setTimeout(()=> {
res.json({
name: "穿山甲"
});
},3000);
});
router.get('/getName3', function(req, res, next) {
res.json({
name: "你先喝"
});
});
嗯嗯,就这样咯,有问题请指正;
觉得有用就给个赞吧