摘要:而和的延遲明顯是小于的。因?yàn)榈氖录C(jī)制是通過(guò)事件隊(duì)列來(lái)調(diào)度執(zhí)行,會(huì)等主進(jìn)程執(zhí)行空閑后進(jìn)行調(diào)度,所以先回去等待所有的進(jìn)程執(zhí)行完成之后再去一次更新。因?yàn)槭紫扔|發(fā)了,導(dǎo)致觸發(fā)了的,從而將更新操作進(jìn)入的事件隊(duì)列。這種情況會(huì)導(dǎo)致順序成為了。
背景
我們先來(lái)看一段Vue的執(zhí)行代碼:
export default { data () { return { msg: 0 } }, mounted () { this.msg = 1 this.msg = 2 this.msg = 3 }, watch: { msg () { console.log(this.msg) } } }
這段腳本執(zhí)行我們猜測(cè)1000m后會(huì)依次打?。?、2、3。但是實(shí)際效果中,只會(huì)輸出一次:3。為什么會(huì)出現(xiàn)這樣的情況?我們來(lái)一探究竟。
queueWatcher我們定義watch監(jiān)聽msg,實(shí)際上會(huì)被Vue這樣調(diào)用vm.$watch(keyOrFn, handler, options)。$watch是我們初始化的時(shí)候,為vm綁定的一個(gè)函數(shù),用于創(chuàng)建Watcher對(duì)象。那么我們看看Watcher中是如何處理handler的:
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) } } ...
初始設(shè)定this.deep = this.user = this.lazy = this.sync = false,也就是當(dāng)觸發(fā)update更新的時(shí)候,會(huì)去執(zhí)行queueWatcher方法:
const queue: Array= [] 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函數(shù)其實(shí)就是watcher的視圖更新:
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() ... } }
另外,關(guān)于waiting變量,這是很重要的一個(gè)標(biāo)志位,它保證flushSchedulerQueue回調(diào)只允許被置入callbacks一次。
接下來(lái)我們來(lái)看看nextTick函數(shù),在說(shuō)nexTick之前,需要你對(duì)Event Loop、microTask、macroTask有一定的了解,Vue nextTick 也是主要用到了這些基礎(chǔ)原理。如果你還不了解,可以參考我的這篇文章Event Loop 簡(jiǎn)介
好了,下面我們來(lái)看一下他的實(shí)現(xiàn):
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通過(guò)callback數(shù)組來(lái)模擬事件隊(duì)列,事件隊(duì)里的事件,通過(guò)nextTickHandler方法來(lái)執(zhí)行調(diào)用,而何事進(jìn)行執(zhí)行,是由timerFunc來(lái)決定的。我們來(lái)看一下timeFunc的定義:
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的定義優(yōu)先順序macroTask --> microTask,在沒(méi)有Dom的環(huán)境中,使用microTask,比如weex
setImmediate、MessageChannel VS setTimeout我們是優(yōu)先定義setImmediate、MessageChannel為什么要優(yōu)先用他們創(chuàng)建macroTask而不是setTimeout?
HTML5中規(guī)定setTimeout的最小時(shí)間延遲是4ms,也就是說(shuō)理想環(huán)境下異步回調(diào)最快也是4ms才能觸發(fā)。Vue使用這么多函數(shù)來(lái)模擬異步任務(wù),其目的只有一個(gè),就是讓回調(diào)異步且盡早調(diào)用。而MessageChannel 和 setImmediate 的延遲明顯是小于setTimeout的。
有了這些基礎(chǔ),我們?cè)倏匆槐樯厦嫣岬降膯?wèn)題。因?yàn)?b>Vue的事件機(jī)制是通過(guò)事件隊(duì)列來(lái)調(diào)度執(zhí)行,會(huì)等主進(jìn)程執(zhí)行空閑后進(jìn)行調(diào)度,所以先回去等待所有的進(jìn)程執(zhí)行完成之后再去一次更新。這樣的性能優(yōu)勢(shì)很明顯,比如:
現(xiàn)在有這樣的一種情況,mounted的時(shí)候test的值會(huì)被++循環(huán)執(zhí)行1000次。 每次++時(shí),都會(huì)根據(jù)響應(yīng)式觸發(fā)setter->Dep->Watcher->update->run。 如果這時(shí)候沒(méi)有異步更新視圖,那么每次++都會(huì)直接操作DOM更新視圖,這是非常消耗性能的。 所以Vue實(shí)現(xiàn)了一個(gè)queue隊(duì)列,在下一個(gè)Tick(或者是當(dāng)前Tick的微任務(wù)階段)的時(shí)候會(huì)統(tǒng)一執(zhí)行queue中Watcher的run。同時(shí),擁有相同id的Watcher不會(huì)被重復(fù)加入到該queue中去,所以不會(huì)執(zhí)行1000次Watcher的run。最終更新視圖只會(huì)直接將test對(duì)應(yīng)的DOM的0變成1000。 保證更新視圖操作DOM的動(dòng)作是在當(dāng)前棧執(zhí)行完以后下一個(gè)Tick(或者是當(dāng)前Tick的微任務(wù)階段)的時(shí)候調(diào)用,大大優(yōu)化了性能。
有趣的問(wèn)題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") }) } })
這個(gè)的執(zhí)行順序想必大家都知道先后打印:1、promise、2、3。
因?yàn)槭紫扔|發(fā)了this.msg = "end",導(dǎo)致觸發(fā)了watcher的update,從而將更新操作callback push進(jìn)入vue的事件隊(duì)列。
this.$nextTick也為事件隊(duì)列push進(jìn)入了新的一個(gè)callback函數(shù),他們都是通過(guò)setImmediate --> MessageChannel --> Promise --> setTimeout來(lái)定義timeFunc。而 Promise.resolve().then則是microTask,所以會(huì)先去打印promise。
在支持MessageChannel和setImmediate的情況下,他們的執(zhí)行順序是優(yōu)先于setTimeout的(在IE11/Edge中,setImmediate延遲可以在1ms以內(nèi),而setTimeout有最低4ms的延遲,所以setImmediate比setTimeout(0)更早執(zhí)行回調(diào)函數(shù)。其次因?yàn)槭录?duì)列里,優(yōu)先收入callback數(shù)組)所以會(huì)打印2,接著打印3
但是在不支持MessageChannel和setImmediate的情況下,又會(huì)通過(guò)Promise定義timeFunc,也是老版本Vue 2.4 之前的版本會(huì)優(yōu)先執(zhí)行promise。這種情況會(huì)導(dǎo)致順序成為了:1、2、promise、3。因?yàn)閠his.msg必定先會(huì)觸發(fā)dom更新函數(shù),dom更新函數(shù)會(huì)先被callback收納進(jìn)入異步時(shí)間隊(duì)列,其次才定義Promise.resolve().then(function () { console.log("promise!")})這樣的microTask,接著定義$nextTick又會(huì)被callback收納。我們知道隊(duì)列滿足先進(jìn)先出的原則,所以優(yōu)先去執(zhí)行callback收納的對(duì)象。
后記如果你對(duì)Vue源碼感興趣,可以來(lái)這里:
更多好玩的Vue約定源碼解釋
參考文章:
Vue.js 升級(jí)踩坑小記
【Vue源碼】Vue中DOM的異步更新策略以及nextTick機(jī)制
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/52280.html
摘要:在查詢了各種資料后,總結(jié)了一下其原理和用途,如有錯(cuò)誤,請(qǐng)不吝賜教。截取關(guān)鍵部分如下具體來(lái)說(shuō),異步執(zhí)行的運(yùn)行機(jī)制如下。知乎上的例子改變數(shù)據(jù)想要立即使用更新后的。需要注意的是,在和階段,如果需要操作渲染后的試圖,也要使用方法。 對(duì)于 Vue.nextTick 方法,自己有些疑惑。在查詢了各種資料后,總結(jié)了一下其原理和用途,如有錯(cuò)誤,請(qǐng)不吝賜教。 概覽 官方文檔說(shuō)明: 用法: 在下次 DO...
摘要:而和的延遲明顯是小于的。因?yàn)榈氖录C(jī)制是通過(guò)事件隊(duì)列來(lái)調(diào)度執(zhí)行,會(huì)等主進(jìn)程執(zhí)行空閑后進(jìn)行調(diào)度,所以先回去等待所有的進(jìn)程執(zhí)行完成之后再去一次更新。因?yàn)槭紫扔|發(fā)了,導(dǎo)致觸發(fā)了的,從而將更新操作進(jìn)入的事件隊(duì)列。這種情況會(huì)導(dǎo)致順序成為了。 背景 我們先來(lái)看一段Vue的執(zhí)行代碼: export default { data () { return { msg: 0 ...
摘要:復(fù)制代碼然后在這個(gè)文件里還有一個(gè)函數(shù)叫用來(lái)把保存的回調(diào)函數(shù)給全執(zhí)行并清空。其實(shí)調(diào)用的不僅是開發(fā)者,更新時(shí),也用到了。但是問(wèn)題又來(lái)了,根據(jù)瀏覽器的渲染機(jī)制,渲染線程是在微任務(wù)執(zhí)行完成之后運(yùn)行的。 當(dāng)在代碼中更新了數(shù)據(jù),并希望等到對(duì)應(yīng)的Dom更新之后,再執(zhí)行一些邏輯。這時(shí),我們就會(huì)用到$nextTickfuncion call...
摘要:本篇文章主要是對(duì)中的異步更新策略和機(jī)制的解析,需要讀者有一定的使用經(jīng)驗(yàn)并且熟悉掌握事件循環(huán)模型。這個(gè)結(jié)果足以說(shuō)明中的更新并非同步。二是把回調(diào)函數(shù)放入一個(gè)隊(duì)列,等待適當(dāng)?shù)臅r(shí)機(jī)執(zhí)行。通過(guò)的主動(dòng)來(lái)觸發(fā)的事件,進(jìn)而把回調(diào)函數(shù)作為參與事件循環(huán)。 本篇文章主要是對(duì)Vue中的DOM異步更新策略和nextTick機(jī)制的解析,需要讀者有一定的Vue使用經(jīng)驗(yàn)并且熟悉掌握J(rèn)avaScript事件循環(huán)模型。 ...
閱讀 4018·2021-10-09 09:43
閱讀 2901·2021-10-08 10:05
閱讀 2774·2021-09-08 10:44
閱讀 905·2019-08-30 15:52
閱讀 2852·2019-08-26 17:01
閱讀 3046·2019-08-26 13:54
閱讀 1681·2019-08-26 10:48
閱讀 833·2019-08-23 14:41