data () {
return {
num: 0, // 第几次懒加载
stockCode: [],
promises: [],
stocks: [],
arr: {},
}
},
computed: {
start () {
return 0 + 20 * this.num
},
end () {
return 20 + 20 * this.num
},
scrollTop () {
return 148 * 14 + 148 * 20 * this.num
},
tatalData () {
let stockCode = []
for (let i in this.arr) {
for (let j in this.arr[i]) {
if (this.arr[i][j].stockCode) {
this.stocks.push(this.arr[i][j].stockCode)
let code = appendMarketCode(this.arr[i][j].stockCode)
stockCode.push(code)
}
}
}
return stockCode
}
},
watch: {
stockCode (val) {
console.info('code', val)
this.kXian = {}
this.promises = val.map(value => {
return this.getDayK(value)
})
}
},
methods: {
onScroll () {
let scrollTop = document.getElementsByTagName('body')[0].scrollTop
if (scrollTop > this.scrollTop) {
this.num++
this.getStockCode(this.start, this.end)
Promise.all(this.promises).then(() => {
this.KX = Object.assign({}, this.KX, this.kXian)
console.info('cg', this.kXian)
})
}
},
getStockCode (start = 0, end = 20) {
this.stockCode = this.tatalData.slice(start, end)
},
当我的onscroll方法执行时,先是this.num++,然后执行getStickcode方法前compouted中的方法已经执行完毕,之后会先执行完promise.all中的方法,再去执行watch中的方法。我的解决方法是promise.all之外包一层settimeout,这样就能使得先执行watch中的函数在执行promise中的函数。问题虽然解决了但是我对于computed和watch方法的执行顺序却依然不明白,求各位大佬讲讲实现computed和watch的实现原理
在vue官方文档的深入响应式原理一节有相关的解释https://cn.vuejs.org/v2/guide...
watch
是异步的,promise.all
是同步代码,所以当然会在watch前执行将
promise.all
放入this.$nextTick()
中也许可以帮助你解决问题。