前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >多个请求下 loading 的展示与关闭

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

作者头像
谭光志
发布2020-09-28 10:42:52
2.2K0
发布2020-09-28 10:42:52
举报
文章被收录于专栏:编程技术分享编程技术分享

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

代码语言:javascript
复制
    <div class="app">
        <keep-alive :include="keepAliveData">
            <router-view/>
        </keep-alive>
        <div class="loading" v-show="isShowLoading">
            <Spin size="large"></Spin>
        </div>
    </div>

同时设置 axios 拦截器。

代码语言:javascript
复制
 // 添加请求拦截器
 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。 如果每次只有一个请求,这样运行是没问题的。但同时有多个请求并发,就会有问题了。

举例

假如现在同时发起两个请求,在请求前,拦截器 this.isShowLoading = true 将 loading 打开。 现在有一个请求结束了。this.isShowLoading = false 拦截器关闭 loading,但是另一个请求由于某些原因并没有结束。 造成的后果就是页面请求还没完成,loading 却关闭了,用户会以为页面加载完成了,结果页面不能正常运行,导致用户体验不好。

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

代码语言:javascript
复制
loadingCount: 0

再增加两个方法,来对 loadingCount 进行增减操作。

代码语言:javascript
复制
    methods: {
        addLoading() {
            this.isShowLoading = true
            this.loadingCount++
        },

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

现在拦截器变成这样:

代码语言:javascript
复制
        // 添加请求拦截器
        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 关闭的问题。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档