鍍金池/ 問答/HTML5  HTML/ vue中的computed和watch以及方法中的promise執(zhí)行順序問題

vue中的computed和watch以及方法中的promise執(zhí)行順序問題

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)
},

當(dāng)我的onscroll方法執(zhí)行時,先是this.num++,然后執(zhí)行g(shù)etStickcode方法前compouted中的方法已經(jīng)執(zhí)行完畢,之后會先執(zhí)行完promise.all中的方法,再去執(zhí)行watch中的方法。我的解決方法是promise.all之外包一層settimeout,這樣就能使得先執(zhí)行watch中的函數(shù)在執(zhí)行promise中的函數(shù)。問題雖然解決了但是我對于computed和watch方法的執(zhí)行順序卻依然不明白,求各位大佬講講實(shí)現(xiàn)computed和watch的實(shí)現(xiàn)原理

回答
編輯回答
逗婦乳

在vue官方文檔的深入響應(yīng)式原理一節(jié)有相關(guān)的解釋https://cn.vuejs.org/v2/guide...

watch是異步的,promise.all是同步代碼,所以當(dāng)然會在watch前執(zhí)行
promise.all放入this.$nextTick()中也許可以幫助你解決問題。

2017年3月2日 01:20