1.这是加载动画的开启和关闭的函数,needLoadingRequestCount 计数器是处理多个异步请求的动画
function startLoading() { //使用Element loading-start 方法
loading = Loading.service({
lock: true,
text: '拼命加载中...',
background: 'rgba(0, 0, 0, 0.7)'
})
}
function endLoading() { //使用Element loading-close 方法
loading.close()
}
//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
let now
let max_quriue_time =300
let count =false
function showFullScreenLoading() {
now = Date.now();
if (needLoadingRequestCount === 0) {
count=true;
startLoading();
}
needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
if(count){
endLoading();
}
if (needLoadingRequestCount <= 0) return;
needLoadingRequestCount--;
if (needLoadingRequestCount === 0) {
max_quriue_time=Date.now()-now
if(count){
endLoading();
}
}
};
- 同步请求(需要在回调里面再次请求),就会发现,请求的动画,会在网速很快的时候,出现连续的加载动画的开启和关闭,页面就会闪烁了,解决方法是在请求头加上isshowLoading属性来判断是否要加载动画,就是(get(url,header:{isshowLoading:true})。不好的地方就是页面的请求动画可能和加载完成才做的事情有点,可能加载动画提前结束或迟了开启。
service.interceptors.request.use(config => {
console.log(config.headers.isshowLoading,"考难料")
//config.headers.isshowLoading 是否要加载的动画
if(config.headers.isshowLoading){
// alert(1)
}else{
showFullScreenLoading()
}
//设置
config.headers.token = window.sessionStorage.getItem('token')
// config.headers.token = "123456"
// console.log(window.sessionStorage.getItem('token'),"有没有啊")
if (localStorage.eleToken)
config.headers.Authorization = localStorage.eleToken
return config
}, error => {
// endLoading()
return Promise.reject(error)
})
// 响应拦截 401 token过期处理
service.interceptors.response.use(response => {
// console.log(response,2222)
window.sessionStorage.setItem('token',response.headers.token)
// endLoading()
tryHideFullScreenLoading()
//如果token过期了,要求用户重新登录
if(response.headers.token=='undefined'){
Message.error('token值无效,请重新登录')
setTimeout(() => {
// 清除token
localStorage.removeItem('eleToken')
// 页面跳转
router.push('/login')
}, 1000);
}
return response
}
(也在找更好的解决方法,那个朋友有更好的解决方法)109951164313020173.jpg