接口请求添加通用 loading 样式
parent
81d41c6416
commit
05aea0c610
|
@ -0,0 +1,21 @@
|
||||||
|
import { Loading } from 'element-ui'
|
||||||
|
|
||||||
|
let loadingInstance
|
||||||
|
export const loading = {
|
||||||
|
loadingCount: 0,
|
||||||
|
open() {
|
||||||
|
this.loadingCount === 0 && (loadingInstance = Loading.service({
|
||||||
|
lock: true,
|
||||||
|
text: '加载中',
|
||||||
|
spinner: 'el-icon-loading',
|
||||||
|
background: 'rgba(0, 0, 0, 0.7)'
|
||||||
|
}))
|
||||||
|
this.loadingCount++
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
setTimeout(() => {
|
||||||
|
this.loadingCount--
|
||||||
|
this.loadingCount === 0 && loadingInstance && loadingInstance.close()
|
||||||
|
}, 20)
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,6 +3,7 @@ import { MessageBox, Message } from 'element-ui'
|
||||||
import store from '@/store'
|
import store from '@/store'
|
||||||
import { getToken } from '@/utils/auth'
|
import { getToken } from '@/utils/auth'
|
||||||
import router from '@/router'
|
import router from '@/router'
|
||||||
|
import { loading } from './loading'
|
||||||
|
|
||||||
// create an axios instance
|
// create an axios instance
|
||||||
const service = axios.create({
|
const service = axios.create({
|
||||||
|
@ -15,6 +16,7 @@ const service = axios.create({
|
||||||
service.interceptors.request.use(
|
service.interceptors.request.use(
|
||||||
config => {
|
config => {
|
||||||
// do something before request is sent
|
// do something before request is sent
|
||||||
|
loading.open()
|
||||||
|
|
||||||
if (store.getters.token) {
|
if (store.getters.token) {
|
||||||
// let each request carry token
|
// let each request carry token
|
||||||
|
@ -25,6 +27,7 @@ service.interceptors.request.use(
|
||||||
return config
|
return config
|
||||||
},
|
},
|
||||||
error => {
|
error => {
|
||||||
|
loading.close()
|
||||||
// do something with request error
|
// do something with request error
|
||||||
console.log(error) // for debug
|
console.log(error) // for debug
|
||||||
return Promise.reject(error)
|
return Promise.reject(error)
|
||||||
|
@ -44,6 +47,7 @@ service.interceptors.response.use(
|
||||||
* You can also judge the status by HTTP Status Code
|
* You can also judge the status by HTTP Status Code
|
||||||
*/
|
*/
|
||||||
response => {
|
response => {
|
||||||
|
loading.close()
|
||||||
const res = response
|
const res = response
|
||||||
// if the custom code is not 20000, it is judged as an error.
|
// if the custom code is not 20000, it is judged as an error.
|
||||||
if (res.status !== 200) {
|
if (res.status !== 200) {
|
||||||
|
|
Loading…
Reference in New Issue