More Articles
In general, the axios vue incorporated interceptor display control loading and closing, is such that:
in App.vue
the configuration a global loading.
<div class="app">
<keep-alive :include="keepAliveData">
<router-view/>
</keep-alive>
<div class="loading" v-show="isShowLoading">
<Spin size="large"></Spin>
</div>
</div>
And set axios interceptors.
// 添加请求拦截器
this.$axios.interceptors.request.use(config => {
this.isShowLoading = true
return config
}, error => {
this.isShowLoading = false
return Promise.reject(error)
})
// 添加响应拦截器
this.$axios.interceptors.response.use(response => {
this.isShowLoading = false
return response
}, error => {
this.isShowLoading = false
return Promise.reject(error)
})
The interceptor function is requested before the loading opening, closing loading end of the request or an error.
If only one request, this operation is no problem. But at the same time there are multiple simultaneous requests, there will be a problem.
For example :
If two requests initiated concurrently, prior to the request, the interceptor this.isShowLoading = true
will open loading.
Now a request is over. this.isShowLoading = false
Interceptors close loading, but another request for some reason does not end there.
The consequences of that page request is not yet complete, loading it closed, users will think the page load is complete, the results page does not work, causing the user experience is not good.
Solutions
to add a loadingCount
variable number of requests for calculation.
loadingCount: 0
Add two methods, to be loadingCount
increased or decreased operation.
methods: {
addLoading() {
this.isShowLoading = true
this.loadingCount++
},
isCloseLoading() {
this.loadingCount--
if (this.loadingCount == 0) {
this.isShowLoading = false
}
}
}
Now interceptor become like this:
// 添加请求拦截器
this.$axios.interceptors.request.use(config => {
this.addLoading()
return config
}, error => {
this.isShowLoading = false
this.loadingCount = 0
this.$Message.error('网络异常,请稍后再试')
return Promise.reject(error)
})
// 添加响应拦截器
this.$axios.interceptors.response.use(response => {
this.isCloseLoading()
return response
}, error => {
this.isShowLoading = false
this.loadingCount = 0
this.$Message.error('网络异常,请稍后再试')
return Promise.reject(error)
})
The interceptor function is:
Whenever a request is initiated, open loading, at the same time loadingCount
plus 1.
Whenever the end of a request, loadingCount
by 1, and determines loadingCount
whether 0, if is 0, the off loading.
This can be solved, there are multiple requests at a request early termination, resulting in off loading problem.