前言
異步更新是 Vue 核心實作之一,在整體流程中充當著 watcher 更新的調度者這一角色,大部分 watcher 更新都會經過它的處理,在適當時機讓更新有序的執行,而 nextTick 作為異步更新的核心,也是需要學習的重點,
本文你能學習到:
- 異步更新的作用
- nextTick原理
- 異步更新流程
JS運行機制
在理解異步更新前,需要對JS運行機制有些了解,如果你已經知道這些知識,可以選擇跳過這部分內容,
JS 執行是單執行緒的,它是基于事件回圈的,事件回圈大致分為以下幾個步驟:
- 所有同步任務都在主執行緒上執行,形成一個執行堆疊(execution context stack),
- 主執行緒之外,還存在一個"任務佇列"(task queue),只要異步任務有了運行結果,就在"任務佇列"之中放置一個事件,
- 一旦"執行堆疊"中的所有同步任務執行完畢,系統就會讀取"任務佇列",看看里面有哪些事件,那些對應的異步任務,于是結束等待狀態,進入執行堆疊,開始執行,
- 主執行緒不斷重復上面的第三步,
“任務佇列”中的任務(task)被分為兩類,分別是宏任務(macro task)和微任務(micro task)
宏任務:在一次新的事件回圈的程序中,遇到宏任務時,宏任務將被加入任務佇列,但需要等到下一次事件回圈才會執行,常見的宏任務有 setTimeout、setImmediate、requestAnimationFrame
微任務:當前事件回圈的任務佇列為空時,微任務佇列中的任務就會被依次執行,在執行程序中,如果遇到微任務,微任務被加入到當前事件回圈的微任務佇列中,簡單來說,只要有微任務就會繼續執行,而不是放到下一個事件回圈才執行,常見的微任務有 MutationObserver、Promise.then
總的來說,在事件回圈中,微任務會先于宏任務執行,而在微任務執行完后會進入瀏覽器更新渲染階段,所以在更新渲染前使用微任務會比宏任務快一些,
關于事件回圈和瀏覽器渲染可以看下 晨曦時夢見兮 大佬的文章 《深入決議你不知道的 EventLoop 和瀏覽器渲染、幀影片、空閑回呼(動圖演示)》
為什么需要異步更新
既然異步更新是核心之一,首先要知道它的作用是什么,解決了什么問題,
先來看一個很常見的場景:
created(){
this.id = 10
this.list = []
this.info = {}
}
總所周知,Vue 基于資料驅動視圖,資料更改會觸發 setter 函式,通知 watcher 進行更新,如果像上面的情況,是不是代表需要更新3次,而且在實際開發中的更新可不止那么少,更新程序是需要經過繁雜的操作,例如模板編譯、dom diff,頻繁進行更新的性能當然很差,
Vue 作為一個優秀的框架,當然不會那么“直男”,來多少就照單全收,Vue 內部實際是將 watcher 加入到一個 queue 陣列中,最后再觸發 queue 中所有 watcher 的 run 方法來更新,并且加入 queue 的程序中還會對 watcher 進行去重操作,因為在一個組件中 data 內定義的資料都是存盤同一個 “渲染watcher”,所以以上場景中資料即使更新了3次,最終也只會執行一次更新頁面的邏輯,
為了達到這種效果,Vue 使用異步更新,等待所有資料同步修改完成后,再去執行更新邏輯,
nextTick 原理
異步更新內部是最重要的就是 nextTick 方法,它負責將異步任務加入佇列和執行異步任務,Vue 也將它暴露出來提供給用戶使用,在資料修改完成后,立即獲取相關DOM還沒那么快更新,使用 nextTick 便可以解決這一問題,
認識 nextTick
官方檔案對它的描述:
在下次 DOM 更新回圈結束之后執行延遲回呼,在修改資料之后立即使用這個方法,獲取更新后的 DOM,
// 修改資料
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,接下來我們來看一下它的實作,先從入口函式開始:
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
})
}
}
cb即傳入的回呼,它被push進一個callbacks陣列,等待呼叫,pending的作用就是一個鎖,防止后續的nextTick重復執行timerFunc,timerFunc內部創建會一個微任務或宏任務,等待所有的nextTick同步執行完成后,再去執行callbacks內的回呼,- 如果沒有傳入回呼,用戶可能使用的是
Promise形式,回傳一個Promise,_resolve被呼叫時進入到then,
繼續往下走看看 timerFunc 的實作:
// 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 = https://www.cnblogs.com/chanwahfung/p/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 的函式,
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
// 原始碼位置: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 加入佇列
// 原始碼位置: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)
}
}
}
- 每個
watcher都有自己的id,當has沒有記錄到對應的watcher,即第一次進入邏輯,否則是重復的watcher, 則不會進入,這一步就是實作watcher去重的點, - 將
watcher加入到佇列中,等待執行 waiting的作用是防止nextTick重復執行
flushSchedulerQueue 作為回呼傳入 nextTick 異步執行,
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 重置狀態,等待下一輪的異步更新,
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,
往期 Vue 原始碼相關文章:
- 手摸手帶你理解Vue回應式原理
- 手摸手帶你理解Vue的Computed原理
- 手摸手帶你理解Vue的Watch原理
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/39161.html
標籤:JavaScript
上一篇:35.陣列.選擇排序
