實(shí)現(xiàn)全局loading加載
分析需求,我們只需要在請(qǐng)求發(fā)起的時(shí)候開始loading港谊,響應(yīng)結(jié)束的時(shí)候關(guān)閉loading
import axios from 'axios';
import { Message, Loading } from 'element-ui'; //項(xiàng)目已經(jīng)全局引入element的話可以不單獨(dú)引入
import Cookies from 'js-cookie';
import router from '@/router/index'
let loading //定義loading變量
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()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事兒就是將同一時(shí)刻的請(qǐng)求合并。
//聲明一個(gè)變量 needLoadingRequestCount松靡,每次調(diào)用showFullScreenLoading方法 needLoadingRequestCount + 1允跑。
//調(diào)用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1兰绣。needLoadingRequestCount為 0 時(shí)世分,結(jié)束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading()
}
needLoadingRequestCount++
}
export function tryHideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
}
//http request 攔截器
axios.interceptors.request.use(
config => {
var token = ''
if(typeof Cookies.get('user') === 'undefined'){
//此時(shí)為空
}else {
token = JSON.parse(Cookies.get('user')).token
}//注意使用的時(shí)候需要引入cookie方法缀辩,推薦js-cookie
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type':'application/json'
}
if(token != ''){
config.headers.token = token;
}
showFullScreenLoading()
return config;
},
error => {
return Promise.reject(err);
}
);
//http response 攔截器
axios.interceptors.response.use(
response => {
//當(dāng)返回信息為未登錄或者登錄失效的時(shí)候重定向?yàn)榈卿涰?yè)面
if(response.data.code == 'W_100004' || response.data.message == '用戶未登錄或登錄超時(shí)臭埋,請(qǐng)登錄!'){
router.push({
path:"/",
querry:{redirect:router.currentRoute.fullPath}//從哪個(gè)頁(yè)面跳轉(zhuǎn)
})
}
tryHideFullScreenLoading()
return response;
},
error => {
return Promise.reject(error)
}
)
作者:周搏
來源:CSDN
原文:https://blog.csdn.net/web_youth/article/details/80052814
版權(quán)聲明:本文為博主原創(chuàng)文章臀玄,轉(zhuǎn)載請(qǐng)附上博文鏈接瓢阴!