Vue nextTick 機制

背景

我們先來看一段Vue的實行代碼:

export default {
  data () {
    return {
      msg: 0
    }
  },
  mounted () {
    this.msg = 1
    this.msg = 2
    this.msg = 3
  },
  watch: {
    msg () {
      console.log(this.msg)
    }
  }
}

這段劇本實行我們猜想1000m後會順次打印:1、2、3。然則實際效果中,只會輸出一次:3。為何會湧現如許的狀況?我們來一探終究。

queueWatcher

我們定義watch監聽msg,實際上會被Vue如許挪用vm.$watch(keyOrFn, handler, options)$watch是我們初始化的時刻,為vm綁定的一個函數,用於建立Watcher對象。那末我們看看Watcher中是怎樣處置懲罰handler的:

this.deep = this.user = this.lazy = this.sync = false
...
  update () {
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }
...

初始設定this.deep = this.user = this.lazy = this.sync = false,也就是當觸發update更新的時刻,會去實行queueWatcher要領:

const queue: Array<Watcher> = []
let has: { [key: number]: ?true } = {}
let waiting = false
let flushing = false
...
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true
      nextTick(flushSchedulerQueue)
    }
  }
}

這裏面的nextTick(flushSchedulerQueue)中的flushSchedulerQueue函數實在就是watcher的視圖更新:

function flushSchedulerQueue () {
  flushing = true
  let watcher, id
  ...
 for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    id = watcher.id
    has[id] = null
    watcher.run()
    ...
  }
}

別的,關於waiting變量,這是很重要的一個標誌位,它保證flushSchedulerQueue回調只允許被置入callbacks一次。
接下來我們來看看nextTick函數,在說nexTick之前,須要你對Event LoopmicroTaskmacroTask有肯定的相識,Vue nextTick 也是重要用到了這些基本道理。假如你還不相識,能夠參考我的這篇文章Event Loop 簡介
好了,下面我們來看一下他的完成:

export const nextTick = (function () {
  const callbacks = []
  let pending = false
  let timerFunc

  function nextTickHandler () {
    pending = false
    const copies = callbacks.slice(0)
    callbacks.length = 0
    for (let i = 0; i < copies.length; i++) {
      copies[i]()
    }
  }

  // An asynchronous deferring mechanism.
  // In pre 2.4, we used to use microtasks (Promise/MutationObserver)
  // but microtasks actually has too high a priority and fires in between
  // supposedly sequential events (e.g. #4521, #6690) or even between
  // bubbling of the same event (#6566). Technically setImmediate should be
  // the ideal choice, but it's not available everywhere; and the only polyfill
  // that consistently queues the callback after all DOM events triggered in the
  // same loop is by using MessageChannel.
  /* istanbul ignore if */
  if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
    timerFunc = () => {
      setImmediate(nextTickHandler)
    }
  } else if (typeof MessageChannel !== 'undefined' && (
    isNative(MessageChannel) ||
    // PhantomJS
    MessageChannel.toString() === '[object MessageChannelConstructor]'
  )) {
    const channel = new MessageChannel()
    const port = channel.port2
    channel.port1.onmessage = nextTickHandler
    timerFunc = () => {
      port.postMessage(1)
    }
  } else
  /* istanbul ignore next */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    // use microtask in non-DOM environments, e.g. Weex
    const p = Promise.resolve()
    timerFunc = () => {
      p.then(nextTickHandler)
    }
  } else {
    // fallback to setTimeout
    timerFunc = () => {
      setTimeout(nextTickHandler, 0)
    }
  }

  return function queueNextTick (cb?: Function, ctx?: Object) {
    let _resolve
    callbacks.push(() => {
      if (cb) {
        try {
          cb.call(ctx)
        } catch (e) {
          handleError(e, ctx, 'nextTick')
        }
      } else if (_resolve) {
        _resolve(ctx)
      }
    })
    if (!pending) {
      pending = true
      timerFunc()
    }
    // $flow-disable-line
    if (!cb && typeof Promise !== 'undefined') {
      return new Promise((resolve, reject) => {
        _resolve = resolve
      })
    }
  }
})()

起首Vue經由過程callback數組來模仿事宜行列,事宜隊里的事宜,經由過程nextTickHandler要領來實行挪用,而何事舉行實行,是由timerFunc來決議的。我們來看一下timeFunc的定義:

  if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
    timerFunc = () => {
      setImmediate(nextTickHandler)
    }
  } else if (typeof MessageChannel !== 'undefined' && (
    isNative(MessageChannel) ||
    // PhantomJS
    MessageChannel.toString() === '[object MessageChannelConstructor]'
  )) {
    const channel = new MessageChannel()
    const port = channel.port2
    channel.port1.onmessage = nextTickHandler
    timerFunc = () => {
      port.postMessage(1)
    }
  } else
  /* istanbul ignore next */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    // use microtask in non-DOM environments, e.g. Weex
    const p = Promise.resolve()
    timerFunc = () => {
      p.then(nextTickHandler)
    }
  } else {
    // fallback to setTimeout
    timerFunc = () => {
      setTimeout(nextTickHandler, 0)
    }
  }

能夠看出timerFunc的定義優先遞次macroTask –> microTask,在沒有Dom的環境中,運用microTask,比方weex

setImmediate、MessageChannel VS setTimeout

我們是優先定義setImmediateMessageChannel為何要優先用他們建立macroTask而不是setTimeout?
HTML5中劃定setTimeout的最小時候耽誤是4ms,也就是說抱負環境下異步回調最快也是4ms才觸發。Vue運用這麼多函數來模仿異步使命,其目標只要一個,就是讓回調異步且儘早挪用。而MessageChannel 和 setImmediate 的耽誤顯著是小於setTimeout的。

解決題目

有了這些基本,我們再看一遍上面提到的題目。由於Vue的事宜機制是經由過程事宜行列來調理實行,會等主歷程實行餘暇后舉行調理,所以先回去守候一切的歷程實行完成今後再去一次更新。如許的機能上風很顯著,比方:

如今有如許的一種狀況,mounted的時刻test的值會被++輪迴實行1000次。 每次++時,都邑依據相應式觸發setter->Dep->Watcher->update->run。 假如這時刻沒有異步更新視圖,那末每次++都邑直接操縱DOM更新視圖,這是異常斲喪機能的。 所以Vue完成了一個queue行列,鄙人一個Tick(或者是當前Tick的微使命階段)的時刻會一致實行queueWatcher的run。同時,具有雷同id的Watcher不會被反覆加入到該queue中去,所以不會實行1000次Watcher的run。終究更新視圖只會直接將test對應的DOM的0變成1000。 保證更新視圖操縱DOM的行動是在當前棧實行完今後下一個Tick(或者是當前Tick的微使命階段)的時刻挪用,大大優化了機能。

風趣的題目

var vm = new Vue({
    el: '#example',
    data: {
        msg: 'begin',
    },
    mounted () {
      this.msg = 'end'
      console.log('1')
      setTimeout(() => { // macroTask
         console.log('3')
      }, 0)
      Promise.resolve().then(function () { //microTask
        console.log('promise!')
      })
      this.$nextTick(function () {
        console.log('2')
      })
  }
})

這個的實行遞次想必人人都曉得前後打印:1、promise、2、3。

  1. 由於起首觸發了this.msg = 'end',致使觸發了watcherupdate,從而將更新操縱callback push進入vue的事宜行列。
  2. this.$nextTick也為事宜行列push進入了新的一個callback函數,他們都是經由過程setImmediate –> MessageChannel –> Promise –> setTimeout來定義timeFunc。而 Promise.resolve().then則是microTask,所以會先去打印promise。
  3. 在支撐MessageChannelsetImmediate的狀況下,他們的實行遞次是優先於setTimeout的(在IE11/Edge中,setImmediate耽誤能夠在1ms之內,而setTimeout有最低4ms的耽誤,所以setImmediate比setTimeout(0)更早實行回調函數。其次由於事宜行列里,優先收入callback數組)所以會打印2,接着打印3
  4. 然則在不支撐MessageChannelsetImmediate的狀況下,又會經由過程Promise定義timeFunc,也是老版本Vue 2.4 之前的版本會優先實行promise。這類狀況會致使遞次成為了:1、2、promise、3。由於this.msg一定先會觸發dom更新函數,dom更新函數會先被callback收納進入異步時候行列,其次才定義Promise.resolve().then(function () { console.log('promise!')})如許的microTask,接着定義$nextTick又會被callback收納。我們曉得行列滿足先進先出的準繩,所以優先去實行callback收納的對象。

跋文

假如你對Vue源碼感興趣,能夠來這裏:

更多好玩的Vue商定源碼詮釋

參考文章:

Vue.js 晉級踩坑小記

【Vue源碼】Vue中DOM的異步更新戰略以及nextTick機制

    原文作者:muwoo
    原文地址: https://segmentfault.com/a/1190000014651331
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞