Vue.nextTick使用和源碼分析

Vue.nextTick的應用場景

Vue 是採用異步的方式執行 DOM 更新。只要觀察到數據變化,Vue 將開啓一個隊列,並緩衝同一事件循環中發生的全部數據改變。而後,在下一個的事件循環中,Vue 刷新隊列並執行頁面渲染工做。因此修改數據後DOM並不會馬上被從新渲染,若是想在數據更新後對頁面執行DOM操做,能夠在數據變化以後當即使用 Vue.nextTick(callback)。
下面這一段摘自vue官方文檔,關於JS 運行機制的說明:vue

JS 執行是單線程的,它是基於事件循環的。事件循環大體分爲如下幾個步驟:
(1)全部同步任務都在主線程上執行,造成一個執行棧(execution context stack)。
(2)主線程以外,還存在一個"任務隊列"(task queue)。只要異步任務有了運行結果,就在"任務隊列"之中放置一個事件。
(3)一旦"執行棧"中的全部同步任務執行完畢,系統就會讀取"任務隊列",看看裏面有哪些事件。那些對應的異步任務,因而結束等待狀態,進入執行棧,開始執行。
(4)主線程不斷重複上面的第三步。

在主線程中執行修改數據這一同步任務,DOM的渲染事件就會被放到「任務隊列」中,當「執行棧」中同步任務執行完畢,本次事件循環結束,系統纔會讀取並執行「任務隊列」中的頁面渲染事件。而Vue.nextTick中的回調函數則會在頁面渲染後才執行。
例子以下:ios

<template>
  <div>
    <div ref="test">{{test}}</div>
  </div>
</template>
// Some code...
data () {
    return {
        test: 'begin'
    };
},
// Some code...
this.test = 'end';
console.log(this.$refs.test.innerText);//"begin"
this.nextTick(() => {
    console.log(this.$refs.test.innerText) //"end"
})

Vue.nextTick實現原理

Vue.nextTick的源碼vue項目/src/core/util/路徑下的next-tick.js文件,文章最後也會貼出完整的源碼
咱們先來看看對於異步調用函數的實現方法:數組

let timerFunc
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

這段代碼首先的檢測運行環境的支持狀況,使用不一樣的異步方法。優先級依次是Promise、MutationObserver、setImmediate和setTimeout。這是根據運行效率來作優先級處理,有興趣能夠去了解一下這幾種方法的差別。總的來講,Event Loop分爲宏任務以及微任務,宏任務耗費的時間是大於微任務的,因此優先使用微任務。例如Promise屬於微任務,而setTimeout就屬於宏任務。最終timerFunc則是咱們調用nextTick函數時要內部會調用的主要方法,那麼flushCallbacks又是什麼呢,咱們在看看flushCallbacks函數:app

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

這個函數比較簡單,就是依次調用callbacks數組裏面的方法。還使用slice()方法複製callbacks數組並把callbacks數組清空,這裏的callbacks數組就是存放主線程執行過程當中的Vue.nextTick()函數所傳的回調函數集合(主線程可能會屢次使用Vue.nextTick()方法)。到這裏就已經實現了根據環境選擇異步方法,並在異步方法中依次調用傳入Vue.nextTick()方法的回調函數。nextTick函數主要就是要將callback函數存在數組callbacks中,並調用timerFunc方法:異步

export function nextTick (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 => {
      _resolve = resolve
    })
  }
}

能夠看到能夠傳入第二個參數做爲回調函數的this。另外若是參數一的條件判斷爲false時則返回一個Promise對象。例如async

Vue.nextTick(null, {value: 'test'})
  .then((data) => {
    console.log(data.value)   // 'test'
  })

這裏還使用了一個優化技巧,用pending來標記異步任務是否被調用,也就是說在同一個tick內只調用一次timerFunc函數,這樣就不會開啓多個異步任務。ide

完整的源碼:函數

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

export let isUsingMicroTask = false

const callbacks = []
let pending = false

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

// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc

// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
    // In problematic UIWebViews, Promise.then doesn't completely break, but
    // it can get stuck in a weird state where callbacks are pushed into the
    // microtask queue but the queue isn't being flushed, until the browser
    // needs to do some other work, e.g. handle a timer. Therefore we can
    // "force" the microtask queue to be flushed by adding an empty timer.
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  // Use MutationObserver where native Promise is not available,
  // e.g. PhantomJS, iOS7, Android 4.4
  // (#6466 MutationObserver is unreliable in IE11)
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Techinically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

export function nextTick (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 => {
      _resolve = resolve
    })
  }
}
相關文章
相關標籤/搜索