Vue你不得不知道的異步更新機制和nextTick原理


Vue你不得不知道的異步更新機制和nextTick原理

 

前言#

異步更新是 Vue 核心實現之一,在整體流程中充當着 watcher 更新的調度者這一角色。大部分 watcher 更新都會經過它的處理,在適當時機讓更新有序的執行。而 nextTick 作為異步更新的核心,也是需要學習的重點。

本文你能學習到:

  • 異步更新的作用
  • nextTick原理
  • 異步更新流程

JS運行機制#

在理解異步更新前,需要對JS運行機制有些了解,如果你已經知道這些知識,可以選擇跳過這部分內容。

JS 執行是單線程的,它是基於事件循環的。事件循環大致分為以下幾個步驟:

  1. 所有同步任務都在主線程上執行,形成一個執行棧(execution context stack)。
  2. 主線程之外,還存在一個"任務隊列"(task queue)。只要異步任務有了運行結果,就在"任務隊列"之中放置一個事件。
  3. 一旦"執行棧"中的所有同步任務執行完畢,系統就會讀取"任務隊列",看看里面有哪些事件。那些對應的異步任務,於是結束等待狀態,進入執行棧,開始執行。
  4. 主線程不斷重復上面的第三步。

“任務隊列”中的任務(task)被分為兩類,分別是宏任務(macro task)和微任務(micro task)

宏任務:在一次新的事件循環的過程中,遇到宏任務時,宏任務將被加入任務隊列,但需要等到下一次事件循環才會執行。常見的宏任務有 setTimeout、setImmediate、requestAnimationFrame

微任務:當前事件循環的任務隊列為空時,微任務隊列中的任務就會被依次執行。在執行過程中,如果遇到微任務,微任務被加入到當前事件循環的微任務隊列中。簡單來說,只要有微任務就會繼續執行,而不是放到下一個事件循環才執行。常見的微任務有 MutationObserver、Promise.then

總的來說,在事件循環中,微任務會先於宏任務執行。而在微任務執行完后會進入瀏覽器更新渲染階段,所以在更新渲染前使用微任務會比宏任務快一些。

關於事件循環和瀏覽器渲染可以看下 晨曦時夢見兮 大佬的文章 《深入解析你不知道的 EventLoop 和瀏覽器渲染、幀動畫、空閑回調(動圖演示)》

為什么需要異步更新#

既然異步更新是核心之一,首先要知道它的作用是什么,解決了什么問題。

先來看一個很常見的場景:

Copy
created(){
    this.id = 10 this.list = [] this.info = {} } 

總所周知,Vue 基於數據驅動視圖,數據更改會觸發 setter 函數,通知 watcher 進行更新。如果像上面的情況,是不是代表需要更新3次,而且在實際開發中的更新可不止那么少。更新過程是需要經過繁雜的操作,例如模板編譯、dom diff,頻繁進行更新的性能當然很差。

Vue 作為一個優秀的框架,當然不會那么“直男”,來多少就照單全收。Vue 內部實際是將 watcher 加入到一個 queue 數組中,最后再觸發 queue 中所有 watcher 的 run 方法來更新。並且加入 queue 的過程中還會對 watcher 進行去重操作,因為在一個 vue 實例中 data 內定義的數據都是存儲同一個 “渲染watcher”,所以以上場景中數據即使更新了3次,最終也只會執行一次更新頁面的邏輯。

為了達到這種效果,Vue 使用異步更新,等待所有數據同步修改完成后,再去執行更新邏輯。

nextTick 原理#

異步更新內部是最重要的就是 nextTick 方法,它負責將異步任務加入隊列和執行異步任務。Vue 也將它暴露出來提供給用戶使用。在數據修改完成后,立即獲取相關DOM還沒那么快更新,使用 nextTick 便可以解決這一問題。

認識 nextTick

官方文檔對它的描述:

在下次 DOM 更新循環結束之后執行延遲回調。在修改數據之后立即使用這個方法,獲取更新后的 DOM。

Copy
// 修改數據 vm.msg = 'Hello' // DOM 還沒有更新 Vue.nextTick(function () { // DOM 更新了 }) // 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示) Vue.nextTick() .then(function () { // DOM 更新了 }) 

nextTick 使用方法有回調和Promise兩種,以上是通過構造函數調用的形式,更常見的是在實例調用 this.$nextTick。它們都是同一個方法。

內部實現

在 Vue 源碼 2.5+ 后,nextTick 的實現單獨有一個 JS 文件來維護它,它的源碼並不復雜,代碼實現不過100行,稍微花點時間就能啃下來。源碼位置在 src/core/util/next-tick.js,接下來我們來看一下它的實現,先從入口函數開始:

Copy
export function nextTick (cb?: Function, ctx?: Object) { let _resolve // 1 callbacks.push(() => { if (cb) { try { cb.call(ctx) } catch (e) { handleError(e, ctx, 'nextTick') } } else if (_resolve) { _resolve(ctx) } }) // 2 if (!pending) { pending = true timerFunc() } // $flow-disable-line // 3 if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve }) } } 
  1. cb 即傳入的回調,它被 push 進一個 callbacks 數組,等待調用。
  2. pending 的作用就是一個鎖,防止后續的 nextTick 重復執行 timerFunctimerFunc 內部創建會一個微任務或宏任務,等待所有的 nextTick 同步執行完成后,再去執行 callbacks 內的回調。
  3. 如果沒有傳入回調,用戶可能使用的是 Promise 形式,返回一個 Promise_resolve 被調用時進入到 then

繼續往下走看看 timerFunc 的實現:

Copy
// 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. // Technically 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) } } 

上面的代碼並不復雜,主要通過一些兼容判斷來創建合適的 timerFunc,最優先肯定是微任務,其次再到宏任務。優先級為 promise.then > MutationObserver > setImmediate > setTimeout。(源碼中的英文說明也很重要,它們能幫助我們理解設計的意義)

我們會發現無論哪種情況創建的 timerFunc,最終都會執行一個 flushCallbacks 的函數。

Copy
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]() } } 

flushCallbacks 里做的事情 so easy,它負責執行 callbacks 里的回調。

好了,nextTick 的源碼就那么多,現在已經知道它的實現,下面再結合異步更新流程,讓我們對它更充分的理解吧。

異步更新流程#

數據被改變時,觸發 watcher.update

Copy
// 源碼位置:src/core/observer/watcher.js update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) // this 為當前的實例 watcher } } 

調用 queueWatcher,將 watcher 加入隊列

Copy
// 源碼位置:src/core/observer/scheduler.js const queue = [] let has = {} let waiting = false let flushing = false let index = 0 export function queueWatcher (watcher: Watcher) { const id = watcher.id // 1 if (has[id] == null) { has[id] = true // 2 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 // 3 if (!waiting) { waiting = true nextTick(flushSchedulerQueue) } } } 
  1. 每個 watcher 都有自己的 id,當 has 沒有記錄到對應的 watcher,即第一次進入邏輯,否則是重復的 watcher, 則不會進入。這一步就是實現 watcher 去重的點。
  2. 將 watcher 加入到隊列中,等待執行
  3. waiting 的作用是防止 nextTick 重復執行

flushSchedulerQueue 作為回調傳入 nextTick 異步執行。

Copy
function flushSchedulerQueue () { currentFlushTimestamp = getNow() flushing = true let watcher, id // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort((a, b) => a.id - b.id) // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index] if (watcher.before) { watcher.before() } id = watcher.id has[id] = null watcher.run() } // keep copies of post queues before resetting state const activatedQueue = activatedChildren.slice() const updatedQueue = queue.slice() resetSchedulerState() // call component updated and activated hooks callActivatedHooks(activatedQueue) callUpdatedHooks(updatedQueue) } 

flushSchedulerQueue 內將剛剛加入 queue 的 watcher 逐個 run 更新。resetSchedulerState 重置狀態,等待下一輪的異步更新。

Copy
function resetSchedulerState () { index = queue.length = activatedChildren.length = 0 has = {} if (process.env.NODE_ENV !== 'production') { circular = {} } waiting = flushing = false } 

要注意此時 flushSchedulerQueue 還未執行,它只是作為回調傳入而已。因為用戶可能也會調用 nextTick 方法。這種情況下,callbacks 里的內容為 ["flushSchedulerQueue", "用戶的nextTick回調"],當所有同步任務執行完成,才開始執行 callbacks 里面的回調。

由此可見,最先執行的是頁面更新的邏輯,其次再到用戶的 nextTick 回調執行。這也是為什么我們能在 nextTick 中獲取到更新后DOM的原因。

總結#

異步更新機制使用微任務或宏任務,基於事件循環運行,在 Vue 中對性能起着至關重要的作用,它對重復冗余的 watcher 進行過濾。而 nextTick 根據不同的環境,使用優先級最高的異步任務。這樣做的好處是等待所有的狀態同步更新完畢后,再一次性渲染頁面。用戶創建的 nextTick 運行頁面更新之后,因此能夠獲取更新后的DOM。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM