Vue nextTick 机制
背景
我們先來看一段Vue的執行代碼:
export default {data () {return {msg: 0}},mounted () {this.msg = 1this.msg = 2this.msg = 3},watch: {msg () {console.log(this.msg)}} }這段腳本執行我們猜測會依次打印:1、2、3。但是實際效果中,只會輸出一次:3。為什么會出現這樣的情況?我們來一探究竟。
queueWatcher
我們定義watch監聽msg,實際上會被Vue這樣調用vm.$watch(keyOrFn, handler, options)。$watch是我們初始化的時候,為vm綁定的一個函數,用于創建Watcher對象。那么我們看看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)}} ...初始設定this.deep = this.user = this.lazy = this.sync = false,也就是當觸發update更新的時候,會去執行queueWatcher方法:
const queue: Array<Watcher> = [] let has: { [key: number]: ?true } = {} let waiting = false let flushing = false ... export function queueWatcher (watcher: Watcher) {const id = watcher.idif (has[id] == null) {has[id] = trueif (!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 flushif (!waiting) {waiting = truenextTick(flushSchedulerQueue)}} }這里面的nextTick(flushSchedulerQueue)中的flushSchedulerQueue函數其實就是watcher的視圖更新:
function flushSchedulerQueue () {flushing = truelet watcher, id...for (index = 0; index < queue.length; index++) {watcher = queue[index]id = watcher.idhas[id] = nullwatcher.run()...} }另外,關于waiting變量,這是很重要的一個標志位,它保證flushSchedulerQueue回調只允許被置入callbacks一次。
接下來我們來看看nextTick函數,在說nexTick之前,需要你對Event Loop、microTask、macroTask有一定的了解,Vue nextTick 也是主要用到了這些基礎原理。如果你還不了解,可以參考我的這篇文章Event Loop 簡介
好了,下面我們來看一下他的實現:
首先Vue通過callback數組來模擬事件隊列,事件隊里的事件,通過nextTickHandler方法來執行調用,而何事進行執行,是由timerFunc來決定的。我們來看一下timeFunc的定義:
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {timerFunc = () => {setImmediate(nextTickHandler)}} else if (typeof MessageChannel !== 'undefined' && (isNative(MessageChannel) ||// PhantomJSMessageChannel.toString() === '[object MessageChannelConstructor]')) {const channel = new MessageChannel()const port = channel.port2channel.port1.onmessage = nextTickHandlertimerFunc = () => {port.postMessage(1)}} else/* istanbul ignore next */if (typeof Promise !== 'undefined' && isNative(Promise)) {// use microtask in non-DOM environments, e.g. Weexconst p = Promise.resolve()timerFunc = () => {p.then(nextTickHandler)}} else {// fallback to setTimeouttimerFunc = () => {setTimeout(nextTickHandler, 0)}}可以看出timerFunc的定義優先順序macroTask --> microTask,在沒有Dom的環境中,使用microTask,比如weex
setImmediate、MessageChannel VS setTimeout
我們是優先定義setImmediate、MessageChannel為什么要優先用他們創建macroTask而不是setTimeout?
HTML5中規定setTimeout的最小時間延遲是4ms,也就是說理想環境下異步回調最快也是4ms才能觸發。Vue使用這么多函數來模擬異步任務,其目的只有一個,就是讓回調異步且盡早調用。而MessageChannel 和 setImmediate 的延遲明顯是小于setTimeout的。
解決問題
有了這些基礎,我們再看一遍上面提到的問題。因為Vue的事件機制是通過事件隊列來調度執行,會等主進程執行空閑后進行調度,所以先回去等待所有的進程執行完成之后再去一次更新。這樣的性能優勢很明顯,比如:
現在有這樣的一種情況,mounted的時候test的值會被++循環執行1000次。 每次++時,都會根據響應式觸發setter->Dep->Watcher->update->run。 如果這時候沒有異步更新視圖,那么每次++都會直接操作DOM更新視圖,這是非常消耗性能的。 所以Vue實現了一個queue隊列,在下一個Tick(或者是當前Tick的微任務階段)的時候會統一執行queue中Watcher的run。同時,擁有相同id的Watcher不會被重復加入到該queue中去,所以不會執行1000次Watcher的run。最終更新視圖只會直接將test對應的DOM的0變成1000。 保證更新視圖操作DOM的動作是在當前棧執行完以后下一個Tick(或者是當前Tick的微任務階段)的時候調用,大大優化了性能。
有趣的問題
var vm = new Vue({el: '#example',data: {msg: 'begin',},mounted () {this.msg = 'end'console.log('1')setTimeout(() => { // macroTaskconsole.log('3')}, 0)Promise.resolve().then(function () { //microTaskconsole.log('promise!')})this.$nextTick(function () {console.log('2')})} })這個的執行順序想必大家都知道先后打印:1、promise、2、3。
因為首先觸發了this.msg = 'end',導致觸發了watcher的update,從而將更新操作callback push進入vue的事件隊列。
this.$nextTick也為事件隊列push進入了新的一個callback函數,他們都是通過setImmediate --> MessageChannel --> Promise --> setTimeout來定義timeFunc。而Promise.resolve().then則是microTask,所以會先去打印promise。
在支持MessageChannel和setImmediate的情況下,他們的執行順序是優先于setTimeout的(在IE11/Edge中,setImmediate延遲可以在1ms以內,而setTimeout有最低4ms的延遲,所以setImmediate比setTimeout(0)更早執行回調函數。其次因為事件隊列里,優先收入callback數組)所以會打印2,接著打印3
但是在不支持MessageChannel和setImmediate的情況下,又會通過Promise定義timeFunc,也是老版本Vue 2.4 之前的版本會優先執行promise。這種情況會導致順序成為了:1、2、promise、3。因為this.msg必定先會觸發dom更新函數,dom更新函數會先被callback收納進入異步時間隊列,其次才定義Promise.resolve().then(function () { console.log('promise!')})這樣的microTask,接著定義$nextTick又會被callback收納。我們知道隊列滿足先進先出的原則,所以優先去執行callback收納的對象。
后記
如果你對Vue源碼感興趣,可以來這里:
更多好玩的Vue約定源碼解釋
參考文章:
Vue.js 升級踩坑小記
【Vue源碼】Vue中DOM的異步更新策略以及nextTick機制
轉載于:https://www.cnblogs.com/tiedaweishao/p/8967127.html
總結
以上是生活随笔為你收集整理的Vue nextTick 机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基础数学概念
- 下一篇: Unity3D_07_日志、文本打印