源代码如下,问题在于在初始化的时候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