element ui加載中組件
很多時候,頁面在調取接口時,需要時間,此時爲了頁面有更好的交互性,通常都是有個加載中的顯示,等頁面渲染完成後,加載中消失。
element ui中loading組件的使用方法:
在哪個頁面中需要使用,就在哪個頁面中引用。
前提是已經引用了element ui
- 引入element ui中的loading組件
import { Loading } from 'element-ui';
- 定義一個變量接收這個loading
let loadingInstance1 = Loading.service({ fullscreen: true });
- 關閉加載中組件的方法
loadingInstance.close();
下面展示一下在axios攔截器中Loading組件的使用
// response 攔截器\
//定義一個變量接收loading組件
let loadingInstance
service.interceptors.request.use(
//request 請求部分,在這個部分開啓loading組件
config => {
if (getToken()) {
config.headers['Authorization'] = getToken() // 讓每個請求攜帶自定義token 請根據實際情況自行修改
}
config.headers['Content-Type'] = 'application/json'
if (config.type && config.type === 'form') {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
if (config.data) {
config.data = qs.stringify(config.data)
}
}
if (config.loading) {
// eslint-disable-next-line no-const-assign
//這行代碼開始加載中組件,而且是全屏展示
loadingInstance = Loading.service({ fullscreen: true })
}
return config
},
error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
service.interceptors.response.use(
//接收到數據的處理部分,在這個部分關閉loading加載中組件
response => {
const code = response.status
if (code < 200 || code > 300) {
Notification.error({
title: response.message
})
//如果有加載中組件,則關閉
if (loadingInstance) {
loadingInstance.close()
}
return Promise.reject('error')
} else {
if (loadingInstance) {
loadingInstance.close()
}
return response.data
}
},
error => {
let code = 0
try {
code = error.response.data.status
} catch (e) {
if (error.toString().indexOf('Error: timeout') !== -1) {
Notification.error({
title: '網絡請求超時',
duration: 5000
})
return Promise.reject(error)
}
}
if (code) {
if (code === 401) {
MessageBox.confirm(
'登錄狀態已過期,您可以繼續留在該頁面,或者重新登錄',
'系統提示',
{
confirmButtonText: '重新登錄',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.reload() // 爲了重新實例化vue-router對象 避免bug
})
})
} else if (code === 403) {
router.push({ path: '/401' })
} else {
const errorMsg = error.response.data.message
if (errorMsg !== undefined) {
Notification.error({
title: errorMsg,
duration: 5000
})
}
}
} else {
Notification.error({
title: '接口請求失敗',
duration: 5000
})
}
return Promise.reject(error)
}