记录一个十分奇怪的前端关于loading的bug

文章讲述了在Vue项目中,初始化时loading无法正确显示的问题,因为两个异步API调用的时间差导致了loading提前变为false。解决方法包括优化API调用顺序或为相关table添加独立loading。
摘要由CSDN通过智能技术生成

源代码如下,问题在于在初始化的时候loading总是无法正确加载,明明queryAllCoupon中的数据并没有挂载完毕loading却失效了。

      queryAllCoupon () {
        const queryParams = this.getQueryParams()
        this.loading = true
         api.queryAllCoupon(queryParams).then(res => {
          if (res.code === 0) {
           this.couponCodeList = res.result.list
           this.pagination.total = res.result.totalCount
          }
          this.loading = false
         })
      },
      getCouponTypeList () {
        this.loading = true
         api.getCouponTypeList().then(res => {
          this.loading = false
           this.couponTypeList = res.result
         })
      },
        created () {
        this.getCouponTypeList()
        this.queryAllCoupon()
    }

一开始我以为是queryAllCoupon方法中couponCodeList并没有加载完毕就渲染了,但是仔细看了以前的代码发现都是这样写的却没有错,都是在等待数据挂载完毕后再将loading设为false,既然不是vue2挂载数据的问题,那么问题就出在了loading身上,经过一番尝试找到了问题,在我的queryAllCoupon方法中,在我将this.loading设为false之前,loading就已经被设为false了,经过断点测试,接下来将正确的执行顺序标注。

  queryAllCoupon () {
       3  const queryParams = this.getQueryParams()
       4  this.loading = true
        5 api.queryAllCoupon(queryParams).then(res => {
          if (res.code === 0) {
          8 this.couponCodeList = res.result.list
         9  this.pagination.total = res.result.totalCount
          }
        10  this.loading = false
         })
      },
      getCouponTypeList () {
         1 this.loading = true
        2  api.getCouponTypeList().then(res => {
         6 this.loading = false
          7 this.couponTypeList = res.result
         })
      },
        created () {
        this.getCouponTypeList()
        this.queryAllCoupon()
    }

可以看出,在我挂载couponCodeList 的数据之前,loading的值已经被改为了false,之前我一直以为created函数中的执行顺序是同步的,但现在看来也并不是完全同步的,他们只是发送完请求之后就开始执行其他的函数了,以往这样写loading没有出错是因为两个函数执行时间差不多看不出来loading的变化,而这两个函数的执行时间差距很大,一个方法查询只有两条数据,一个有上百万条,导致了时间短的函数先执行完毕先一步更改了loading。解决方法有两个,去掉执行时间短的loading改变,或者couponCodeList对应的table设置另一个loading

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值