上篇文章vue生命周期中我們說過一個句話,那就是mounted中并不會保證所有子組件都被掛載完成后再觸發,因此當你希望視圖完全渲染完成后再做某些事情時,請在mounted中使用$nextTick,那么$nextTick到底是干嘛用的,為什么能解決我們以上的問題,下面我們來好好了解了解$nextTick,但在此之前,如果不懂js事件回圈的人,請先去看下什么是js事件回圈,因為要理解$nextTick,必須得先理解js事件回圈
js事件回圈回顧
下面我們先簡單得回顧下什么是事件回圈(具體理解請看這 js事件回圈)
js處理異步主要有微任務(microTask)和 宏任務 (macroTask),而從開始執行一個宏任務–>執行完這個宏任務中所有同步代碼—>清空當前微任務佇列中所有微任務—> UI渲染 , 這便是完成了一個事件回圈(Tick), 然后開始執行下一個宏任務(相當于下一輪回圈),
Vue異步更新
vue實作dom更新是異步完成的,我們可以從下面這個例子中就能看的出
<body>
<div id="app">
<p ref="dom">{{message}}</p>
<button @click="changeValue">改變值</button>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
message: 'hello world'
},
methods: {
changeValue () {
this.message = 'hello zhangShan'
console.log(this.$refs.dom.innerText)
}
}
})
</script>
輸出值為
hello world
從上圖中,我們可以看出,我們改變了message后,立馬去輸出p標簽的text值,發現還是原來的值,這就很明顯了,vue的dom更新,并不是同步的,而是異步的,所以在輸出時,實際dom還并沒有更新,
那么,為什么要設計成異步的,其實很好理解,如果是同步的,當我們頻繁的去改變狀態值時,是不是會頻繁的導致我們的dom更新啊,這很顯然是不行的,
<body>
<div id="app">
<p ref="dom">{{message}}</p>
<button @click="changeValue">改變值</button>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
message: 'hello world'
},
methods: {
changeValue () {
this.message = 'hello zhangShan'
this.message = 'hello liShi'
this.message = 'hello wangWu'
this.message = 'hello chenLiu'
console.log(this.$refs.dom.innerText)
}
}
})
</script>
像上圖這樣,如果vue同步更新的話,將會造成4次dom更新,故vue是異步dom更新的,且更新原理如下(借用官網的話):
Vue 在更新 DOM 時是異步執行的,只要偵聽到資料變化,Vue 將開啟一個佇列,并緩沖在同一事件回圈中發生的所有資料變更,如果同一個 watcher 被多次觸發,只會被推入到佇列中一次,這種在緩沖時去除重復資料對于避免不必要的計算和 DOM 操作是非常重要的,然后,在下一個的事件回圈“tick”中,Vue 重繪佇列并執行實際 (已去重的) 作業,Vue 在內部對異步佇列嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執行環境不支持,則會采用 setTimeout(fn, 0) 代替,
這句話大部分地方其實都很好理解,我也不做過多的說明,我只說明下這句話中(在下一個的事件回圈"tick"中,vue重繪佇列并執行實際作業),按理的理解,這個下一個事件回圈"tick"其實是個泛指,他并不是指下一個事件回圈,才去重繪佇列,實際重繪佇列是有可能在本次事件回圈的微任務中重繪的,也可能是在下一個事件回圈中重繪的,這取決于代碼當前執行的環境,如若當前執行環境支持promise,那么nextTick內部實際會用Promise去執行,那么佇列重繪就會在本次事件回圈的微任務中去執行,
也就是說,如果當前環境支持promise,那么nextTick內部會使用promise.then去執行,否則,如果支持mutationObserver,那么會用mutationObserver(什么是mutationObserver),不過mutationObserver在vue2.5以后被棄用了,如果這兩種都不支持,才會使用setImmediate,MessageChannel(vue2.5以后才有),或者setTimeout(按順序,支持哪個優先用哪個),
這也就是vue的降級策略
優先選擇微任務microtask(promise和mutationObserver),不支持的情況下,才不得不降級選用宏任務macrotask(setImmediate, MessageChannel, setTimeout),
那么,為什么優先選擇微任務呢
詳情請看 js事件回圈,看完后就會明白,在微任務中更新佇列是會比在宏任務中更新少一次UI渲染的,
下面我們來證實下我們的猜想,請看下面一段代碼
<body>
<div id="app">
<p ref="dom">{{message}}</p>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
message: 'hello world'
},
mounted() {
// 第一步
this.message = 'aaa'
// 第二步
setTimeout(() => {
console.log('222')
})
// 第三步
Promise.resolve().then((res) => {
console.log('333')
})
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom)
})
// 第五步
Promise.resolve().then((res) => {
console.log('555')
})
}
})
</script>
在瀏覽器環境下,輸出如下

首先,從上圖中,我們可以看出
- 第四步優先第二步輸出了 444 和 p標簽,從這里我們可以看出,chrome瀏覽器環境下 nextTick內部是執行了微任務的,所以優先setTimeout輸出了,從這點上是可以驗證我們上面的說法的(至于其他環境下的,我這里就不測驗了)
- 但是,我們還有個疑問,同樣是微任務,為什么第三步的promise會晚于第四步輸出呢,按照我們js事件回圈來看,第三步第四步都是微任務的話,第三步肯定會優先第四步輸出的,但是我們看到的結果卻是第四步優于第三步輸出了,這是為什么呢,其實這個跟我們改變資料觸發watcher更新的先后有關,我們先看下面一段代碼驗證一下是不是跟資料改變觸發watcher更新的順序有關,然后我們再來看為什么跟觸發watcher更新的順序有關,
<body>
<div id="app">
<p ref="dom">{{message}}</p>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
message: 'hello world'
},
mounted() {
// 第二步
setTimeout(() => {
console.log('222')
})
// 第三步
Promise.resolve().then((res) => {
console.log('333')
})
// 第一步
this.message = 'aaa'
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom)
})
// 第五步
Promise.resolve().then((res) => {
console.log('555')
})
}
})
</script>
看上面代碼,這次我們資料更新放到第三步和第四步直接去執行,再看輸出結果

大家發現沒有,這個時候,第三步的微任務是優先執行了的,是不是說明了,nextTick中的callback啥時候執行,取決于資料是在什么時候發生了改變的啊,那么為什么會這樣呢,這我們就要從nextTick原始碼來看看到底是怎么回事了,我們先來看看原始碼
下面的原始碼借鑒于nextTick原始碼實作
首先,我們知道(回應式原理請自行查看MVVM回應式原理或者vue原始碼決議),當回應式資料發生變化時,是不是會觸發它的setter,從而通知Dep去呼叫相關的watch物件,從而觸發watch的update函式進行視圖更新,那我們先看看update函式做了啥
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
/*同步則執行run直接渲染視圖*/
this.run()
} else {
/*異步推送到觀察者佇列中,下一個tick時呼叫,*/
queueWatcher(this)
}
}
update中是不是呼叫了一個queueWatcher方法啊(我們先將update的呼叫稱作第一步,將queueWatcher函式的呼叫稱作第二步,后面用的上),我們再看這個方法做了什么
/*將一個觀察者物件push進觀察者佇列,在佇列中已經存在相同的id則該觀察者物件將被跳過,除非它是在佇列被重繪時推送*/
export function queueWatcher (watcher: Watcher) {
/*獲取watcher的id*/
const id = watcher.id
/*檢驗id是否存在,已經存在則直接跳過,不存在則標記哈希表has,用于下次檢驗*/
if (has[id] == null) {
has[id] = true
if (!flushing) {
/*如果沒有flush掉,直接push到佇列中即可*/
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 >= 0 && queue[i].id > watcher.id) {
i--
}
queue.splice(Math.max(i, index) + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
可以看出,queueWatcher方法內部主要做的就是將watcher push到了queue佇列當中,
同時當waiting為false時,呼叫了一次 nextTick方法, 同時傳入了一個引數 flushSchedulerQueue,其實這個引數,就是具體的佇列更新函式,也就是說更新dom操作就是在這里面做的,而這個waiting狀態的作用,很明顯是為了保證nextTick(flushSchedulerQueue)只會執行一次,后續再通過this.xxx改變資料,只會加入將相關的watcher加入到佇列中,而不會再次執行nextTick(flushSchedulerQueue),
現在我們將nextTick(flushSchedulerQueue) 稱作第三步
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()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
我們再來看看nextTick內部,做了些啥
/**
1. Defer a task to execute it asynchronously.
*/
/*
延遲一個任務使其異步執行,在下一個tick時執行,一個立即執行函式,回傳一個function
這個函式的作用是在task或者microtask中推入一個timerFunc,在當前呼叫堆疊執行完以后以此執行直到執行到timerFunc
目的是延遲到當前呼叫堆疊執行完以后執行
*/
export const nextTick = (function () {
/*存放異步執行的回呼*/
const callbacks = []
/*一個標記位,如果已經有timerFunc被推送到任務佇列中去則不需要重復推送*/
let pending = false
/*一個函式指標,指向函式將被推送到任務佇列中,等到主執行緒任務執行完時,任務佇列中的timerFunc被呼叫*/
let timerFunc
/*下一個tick時的回呼*/
function nextTickHandler () {
/*一個標記位,標記等待狀態(即函式已經被推入任務佇列或者主執行緒,已經在等待當前堆疊執行完畢去執行),這樣就不需要在push多個回呼到callbacks時將timerFunc多次推入任務佇列或者主執行緒*/
pending = false
/*執行所有callback*/
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// 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 if */
/*
這里解釋一下,一共有Promise、MutationObserver以及setTimeout三種嘗試得到timerFunc的方法
優先使用Promise,在Promise不存在的情況下使用MutationObserver,這兩個方法都會在microtask中執行,會比setTimeout更早執行,所以優先使用,
如果上述兩種方法都不支持的環境則會使用setTimeout,在task尾部推入這個函式,等待呼叫執行,
參考:https://www.zhihu.com/question/55364497
*/
if (typeof Promise !== 'undefined' && isNative(Promise)) {
/*使用Promise*/
var p = Promise.resolve()
var logError = err => { console.error(err) }
timerFunc = () => {
p.then(nextTickHandler).catch(logError)
// 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)
}
} else if (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 IE11, iOS7, Android 4.4
/*新建一個textNode的DOM物件,用MutationObserver系結該DOM并指定回呼函式,在DOM變化的時候則會觸發回呼,該回呼會進入主執行緒(比任務佇列優先執行),即textNode.data = String(counter)時便會觸發回呼*/
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
} else {
// fallback to setTimeout
/* istanbul ignore next */
/*使用setTimeout將回呼推入任務佇列尾部*/
timerFunc = () => {
setTimeout(nextTickHandler, 0)
}
}
/*
推送到佇列中下一個tick時執行
cb 回呼函式
ctx 背景關系
*/
return function queueNextTick (cb?: Function, ctx?: Object) {
let _resolve
/*cb存到callbacks中*/
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
timerFunc()
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise((resolve, reject) => {
_resolve = resolve
})
}
}
})()
在這個函式內,我們可以看到
- 首先可以看出,nextTick是一個立即執行函式,也就是說這個函式在定義的時候就已經自動執行一次了,而自動執行時,return function queueNextTick前面的代碼是不是就已經執行了啊,這也是nextTick第一次執行
- 定義了一個函式timerFunc,這是個關鍵函式,因為這個函式是怎樣的,決定了我們的nextTick內部最終是執行了微任務,還是執行了宏任務,(定義nextTick函式時就定義了)
- 定義了一個nextTickHandler函式,這個函式作用很明顯,就是執行我們呼叫nextTick時,所傳進來的callback回呼函式,也就是說當我們執行this.$nextTick(()=> {})時,內部傳遞進來的這個函式,就是在nextTickHandler內被執行的,(定義nextTick函式時就定義了))
- return了一個函式queueNextTick,所以我們可以看出,當我們平常呼叫this.$nextTick(cb)時以及上面呼叫nextTick(flushSchedulerQueue),實際上,是不是呼叫了這個queueNextTick啊, 此時,我們將queueNextTick稱為第四步,
這個時候,我們繼續看queueNextTick,這里做了什么啊
- 將傳入進來的callback回呼函式,push到了callbacks陣列中,為后面nextTickHandler函式執行callback做準備
- 當pending為false時,呼叫了timerFunc函式,此時我們將timerFunc函式的執行,稱為第五步
大家發現沒有,這個pending其實就是解開我們問題的關鍵啊,為什么這么說呢,我們先看timerFunc內做了啥,再回過頭來解釋
那么timerFunc做啥了
if (typeof Promise !== 'undefined' && isNative(Promise)) {
/*使用Promise*/
var p = Promise.resolve()
var logError = err => { console.error(err) }
timerFunc = () => {
p.then(nextTickHandler).catch(logError)
// 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)
}
} else if (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 IE11, iOS7, Android 4.4
/*新建一個textNode的DOM物件,用MutationObserver系結該DOM并指定回呼函式,在DOM變化的時候則會觸發回呼,該回呼會進入主執行緒(比任務佇列優先執行),即textNode.data = String(counter)時便會觸發回呼*/
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
} else {
// fallback to setTimeout
/* istanbul ignore next */
/*使用setTimeout將回呼推入任務佇列尾部*/
timerFunc = () => {
setTimeout(nextTickHandler, 0)
}
}
可以看出,timerFunc內部定義了一些異步函式,視當前執行環境的不同,timerFunc內部執行的異步函式不同,他內部可能是promise, 可能是mutationObserver, 可能是setTimeout,(我們當前例子是在chrome瀏覽器下,timerFunc內部是Promise無疑),但可以看出,不管內部是什么異步函式,它都在異步的回呼中執行了nextTickHandler,而nextTickHandler是決定我們呼叫this.$nextTick(() => {})時,內部回呼函式啥時候執行的關鍵,故可以得出結論,timerFunc內部的異步函式的回呼啥時候執行,我們this.$nextTick()內的回呼就啥時候執行
好,到了這一步,我們就可以來重新梳理下,代碼是怎么走的啦,
mounted() {
// 第一步
this.message = 'aaa'
// 第二步
setTimeout(() => {
console.log('222')
})
// 第三步
Promise.resolve().then((res) => {
console.log('333')
})
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom)
})
// 第五步
Promise.resolve().then((res) => {
console.log('555')
})
}
- this.message = ‘aaa’ 執行,回應式資料發生變化,是不是會觸發setter, 從而進一步觸發watcher的update方法,也就是我們前面說的第一步
- update方法內執行了queueWatcher函式(也就是我們上面說的第二步),將相關watcher push到queue佇列中,并執行了nextTick(flushSchedulerQueue) ,也就是我們上面說的第三步,此時,記住了,我們這里是第一次執行了nextTick方法,此時,我們代碼中的this.$nextTick()還并沒有執行,只執行了this.message = ‘aaa’ , 但是vue內部自動執行了一次nextTick方法,并將flushSchedulerQueue當作引數傳入了
- nexTick內部代碼執行,實際上是執行了queueNextTick,傳入了一個flushSchedulerQueue函式,將這個函式加入到了callbacks陣列中,此時陣列中只有一個cb函式flushSchedulerQueue,
- pending狀態初始為false,故執行了timerFunc,

- timerFunc一旦執行,發現內部是一個promise異步回呼,是不是就加入到微任務佇列了,此時,是不是微任務佇列中的第一個任務啊,但注意,此時,callbacks內的回呼函式還并沒有執行,是不是要等這個微任務執行的時候,callbcaks內的回呼函式才會執行啊
- 此時,跳出原始碼,繼續向下執行我們寫的代碼
mounted() {
// 第一步
this.message = 'aaa'
// 第二步
setTimeout(() => {
console.log('222')
})
// 第三步
Promise.resolve().then((res) => {
console.log('333')
})
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom)
})
// 第五步
Promise.resolve().then((res) => {
console.log('555')
})
}
- 碰到setTimeout,加入宏任務佇列,
- 碰到第一個Promise(console.log(333)的這個), 加入微任務佇列,此時微任務佇列中,是不是就有兩個微任務啦,我們現在加入的這個是第二個
- 此時this.$nextTick()函式執行,相當于就是呼叫了queueNextTick,并傳入了一個回呼函式,此時注意了

之前,我們是不是執行過一次queueNextTick啊,那么pending狀態是不是變為true了,那么timerFunc是不是這個時候不會再執行了,而此時唯一做的操作就是將傳入的回呼函式加入到了callbacks陣列當中,
所以,實際timerFunc這個函式的執行,是在this.message = ‘aaa’ 執行的時候呼叫的,也就意味著,timerFunc內的異步回呼, 是在 this.message = ‘aaa’ 時被加入到了微任務佇列當中,而不是this.$nextTick()執行時被加入到微任務佇列的,所以這也就是前面我們為什么說pending狀態是解決問題的關鍵,因為他決定了,異步回呼啥時候加入到微任務佇列
而this.$nextTick(cb)執行時,唯一的作用就是將cb回呼函式加入到了callbacks陣列當中,那么在微任務佇列被執行的時候,去呼叫callbacks中的回呼函式時,是不是就會呼叫到我們現在加入的這個回呼函式啊 - 繼續,碰到第二個promise(console.log(555)的這個),又加入到微任務佇列中,
- 此時,微任務佇列中存在3個任務,第一個是timerFunc中的promise回呼,第二個是console.log(333)的那個promise回呼,第三個是console.log(555)的那個promise回呼,
- 故,同步代碼執行完成后,優先清空微任務佇列,那么是不是先執行了第一個微任務啊,也就是timeFunc內的那個微任務

而這個微任務一執行,是不是呼叫了nextTickHandler, nextTickHandler是不是就依次執行了callbacks中的回呼函式啊,此時callbacks中有兩個回呼函式,第一個就是flushSchedulerQueue,用于更新dom,第二個就是我們傳進來的這個

所以,我們第二個回呼函式執行時,dom是不是已經更新了啊,然后才輸出 444 和 p標簽 - 然后再取出第二個微任務去執行,就輸出了333
- 再取出第三個微任務去執行,就輸出了555
- 再之后,微任務佇列清空,開始下一輪回圈,取出宏任務佇列中的setTimeout的回呼并執行,輸出222,
這也就是所有的一個執行程序了,講的應該都很明了了,
整體邏輯可能會有點繞,但是認真看,相信你一定能夠看的懂得,看不懂,請私信我,或者直接評論,我會一一解答得,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/244687.html
標籤:其他
