Vue異步更新機制和nextTick原理
作者 | WahFung
來源 | https ://www.cnblogs.com/chanwahfung/p/13296293.html
前言
初步更新的作用
nextTick原理
初步更新流程
js運行機制
所有同步任務(wù)都在主線程上執(zhí)行,形成一個執(zhí)行棧(執(zhí)行上下文堆棧)。
主線程之外,還存在一個“任務(wù)隊列”(task queue)。只要初始化任務(wù)有了運行結(jié)果,就在“任務(wù)變量”之中放置一個事件。
一旦“執(zhí)行棧”中的所有同步任務(wù)執(zhí)行完畢,系統(tǒng)就會重新“任務(wù)類別”,看看里面有什么事件。那些對應的初始化任務(wù),于是結(jié)束等待狀態(tài),進入執(zhí)行棧,開始執(zhí)行。
主線程不斷重復上面的第三步。
為什么需要初步更新
created(){this.id = 10this.list = []this.info = {}}
nextTick原理
認識nextTick
// 修改數(shù)據(jù)vm.msg = 'Hello'// DOM 還沒有更新vue.nextTick(function () {// DOM 更新了})// 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示)vue.nextTick().then(function () {// DOM 更新了})
內(nèi)部實現(xiàn)
export function nextTick (cb?: Function, ctx?: Object) {let _resolve// 1callbacks.push(() => {if (cb) {try {cb.call(ctx)} catch (e) {handleError(e, ctx, 'nextTick')}} else if (_resolve) {_resolve(ctx)}})// 2if (!pending) {pending = truetimerFunc()}// $flow-disable-line// 3if (!cb && typeof Promise !== 'undefined') {return new Promise(resolve => {_resolve = resolve})}}
cb即預期的最大值,它被push進一個回調(diào)回調(diào),等待調(diào)用。
等待的作用就是一個鎖,防止后續(xù)的nextTick重復執(zhí)行timerFunc。timerFunc內(nèi)部創(chuàng)建會一個微任務(wù)或宏任務(wù),等待所有的nextTick同步執(zhí)行完成后,再去執(zhí)行回調(diào)內(nèi)部的替代。
如果沒有預先設(shè)定的,用戶可能使用的是Promise形式,返回一個Promise,_resolve被調(diào)用時進入到。
// 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.xMutationObserver.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 = 1const observer = new MutationObserver(flushCallbacks)const textNode = document.createTextNode(String(counter))observer.observe(textNode, {characterData: true})timerFunc = () => {counter = (counter + 1) % 2textNode.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)}}
const callbacks = []let pending = falsefunction flushCallbacks () {pending = falseconst copies = callbacks.slice(0)callbacks.length = 0for (let i = 0; i < copies.length; i++) {copies[i]()}}
初步更新流程
// 源碼位置:src/core/observer/watcher.jsupdate () {/* istanbul ignore else */if (this.lazy) {this.dirty = true} else if (this.sync) {this.run()} else {queueWatcher(this) // this 為當前的實例 watcher}}
// 源碼位置:src/core/observer/scheduler.jsconst queue = []let has = {}let waiting = falselet flushing = falselet index = 0export function queueWatcher (watcher: Watcher) {const id = watcher.id// 1if (has[id] == null) {has[id] = true// 2if (!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 - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flush// 3if (!waiting) {waiting = truenextTick(flushSchedulerQueue)}}}
每個監(jiān)視者都有他們自己的id,當沒有記錄到對應的監(jiān)視者,即第一次進入邏輯,否則是重復的監(jiān)視者,則不會進入。這一步就是實現(xiàn)監(jiān)視者去重的點。
將watcher加入到體重中,等待執(zhí)行
等待的作用是防止nextTick重復執(zhí)行
function flushSchedulerQueue () {currentFlushTimestamp = getNow()flushing = truelet 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 watchersfor (index = 0; index < queue.length; index++) {watcher = queue[index]if (watcher.before) {watcher.before()}id = watcher.idhas[id] = nullwatcher.run()}// keep copies of post queues before resetting stateconst activatedQueue = activatedChildren.slice()const updatedQueue = queue.slice()resetSchedulerState()// call component updated and activated hookscallActivatedHooks(activatedQueue)callUpdatedHooks(updatedQueue)}
function resetSchedulerState () {index = queue.length = activatedChildren.length = 0has = {}if (process.env.NODE_ENV !== 'production') {circular = {}}waiting = flushing = false}
總結(jié)
評論
圖片
表情
