多个请求下 loading 的展现与关闭

更多文章

通常状况下,在 vue 中结合 axios 的拦截器控制 loading 展现和关闭,是这样的:
App.vue 配置一个全局 loading。html

<div class="app">
        <keep-alive :include="keepAliveData">
            <router-view/>
        </keep-alive>
        <div class="loading" v-show="isShowLoading">
            <Spin size="large"></Spin>
        </div>
    </div>

同时设置 axios 拦截器。vue

// 添加请求拦截器
 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)
 })

这个拦截器的功能是在请求前打开 loading,请求结束或出错时关闭 loading。
若是每次只有一个请求,这样运行是没问题的。但同时有多个请求并发,就会有问题了。ios

举例git

假如如今同时发起两个请求,在请求前,拦截器 this.isShowLoading = true 将 loading 打开。
如今有一个请求结束了。this.isShowLoading = false 拦截器关闭 loading,可是另外一个请求因为某些缘由并无结束。
形成的后果就是页面请求还没完成,loading 却关闭了,用户会觉得页面加载完成了,结果页面不能正常运行,致使用户体验很差。github

解决方案
增长一个 loadingCount 变量,用来计算请求的次数。axios

loadingCount: 0

再增长两个方法,来对 loadingCount 进行增减操做。网络

methods: {
        addLoading() {
            this.isShowLoading = true
            this.loadingCount++
        },

        isCloseLoading() {
            this.loadingCount--
            if (this.loadingCount == 0) {
                this.isShowLoading = false
            }
        }
    }

如今拦截器变成这样:并发

// 添加请求拦截器
        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)
        })

这个拦截器的功能是:
每当发起一个请求,打开 loading,同时 loadingCount 加1。
每当一个请求结束, loadingCount 减1,并判断 loadingCount 是否为 0,若是为 0,则关闭 loading。
这样便可解决,多个请求下有某个请求提早结束,致使 loading 关闭的问题。app

相关文章
相关标签/搜索