Vue nextTick 機制

背景

咱們先來看一段Vue的執行代碼:vue

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

這段腳本執行咱們猜想會依次打印:一、二、3。可是實際效果中,只會輸出一次:3。爲何會出現這樣的狀況?咱們來一探究竟。git

queueWatcher

咱們定義watch監聽msg,實際上會被Vue這樣調用vm.$watch(keyOrFn, handler, options)$watch是咱們初始化的時候,爲vm綁定的一個函數,用於建立Watcher對象。那麼咱們看看Watcher中是如何處理handler的:github

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的視圖更新:promise

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 簡介
好了,下面咱們來看一下他的實現:weex

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的定義:dom

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的。async

解決問題

有了這些基礎,咱們再看一遍上面提到的問題。由於Vue的事件機制是經過事件隊列來調度執行,會等主進程執行空閒後進行調度,因此先回去等待全部的進程執行完成以後再去一次更新。這樣的性能優點很明顯,好比:ide

如今有這樣的一種狀況,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')
      })
  }
})

這個的執行順序想必你們都知道前後打印:一、promise、二、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。這種狀況會致使順序成爲了:一、二、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機制

相關文章
相關標籤/搜索