应用场景
场景:前端在发送Ajax请求,请求后台数据时,不允许用户点击当前页面的其他按钮。
- 引入loading
import { Loading } from 'element-ui'
- 定义全局loading
let loading
function startLoading() {
loading = Loading.service({
fullscreen: true,
background: 'rgba(0, 0, 0, 0)'
})
}
function endLoading() {
loading.close()
}
let needLoadingRequestCount = 0
function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading()
}
needLoadingRequestCount++
}
function tryHideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
}
- 调用
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 30000
})
let checkToken = true
service.interceptors.request.use(
config => {
showFullScreenLoading()
let token = store.getters.token
const diedTime = store.getters.diedTime
const refreshTime = store.getters.refreshTime
if (token) {
let tmp = Date.parse(new Date()).toString()
tmp = tmp.substr(0, 10)
if (tmp >= refreshTime && tmp < diedTime && checkToken) {
checkToken = false
getToken().then(res => {
checkToken = true
store.commit('user/SET_TOKEN', res.data.token)
store.commit('user/SET_DIEDTIME', res.data.died_time)
store.commit('user/SET_REFRESHTIME', res.data.refresh_time)
token = store.getters.token
})
} else if (tmp >= diedTime) {
tryHideFullScreenLoading()
store.commit('user/DEL_TOKEN')
router.replace({
path: '/login'
})
}
config.headers.Authorization = token
}
return config
},
error => {
tryHideFullScreenLoading()
console.log(error)
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
tryHideFullScreenLoading()
const code = response.status
if ((code >= 200 && code < 300) || code === 304) {
return Promise.resolve(response.data)
} else {
return Promise.reject(response)
}
},
error => {
tryHideFullScreenLoading()
if (error.response) {
switch (error.response.status) {
case 401:
Message.error('签名认证已过期,请重新登录!')
router.replace({
path: '/login',
query: {
redirect: '/product-list'
}
})
break
case 404:
Message.error('网络请求不存在')
break
case 422:
Message.error('您的账号已被删除,请联系系统管理员确认情况!')
router.replace({
path: '/login',
query: {
redirect: '/product-list'
}
})
break
case 500:
Message.error('网站后台请求错误')
break
default:
Message.error(error.response.data.message)
}
} else {
if (error.message.includes('timeout')) {
Message.error('请求超时!请检查网络是否正常')
} else {
Message.error('请求失败,请检查网络是否已连接')
}
}
return Promise.reject(error)
}
)