Vue異步更新Dom和$nextTick
$nextTick 的使用場景
雖然 Vue 是數據驅動的,但是有時候我們不得不去操作 DOM 去處理一些特殊的場景,而 Vue 更新 DOM 是異步執行的,所以我們不得不去使用 $nextTick 去異步獲取 DOM。
<template>
<div>
<span ref="msg">{{ msg }}</span>
</div>
</template>
<script>
export default {
data() {
return {
msg: 'hello nextTick'
}
},
methods: {
changeMsg() {
this.msg = 'hello world'
console.log(this.$refs.msg.innerHTML, '同步獲取')
this.$nextTick(() => {
console.log(this.$refs.msg.innerHTML, '異步獲取')
})
}
},
mounted() {
this.changeMsg()
}
}
</script>
我們可以看到,當我我們直接改變數據后,獲取 DOM 的話,值是沒有改變的,而在 $nextTick 中卻可以看到數據發生了變化,為什么呢?下面我們通過源碼看一看原因
Watcher 視圖更新
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
/*同步則執行run直接渲染視圖*/
this.run()
} else {
/*異步推送到觀察者隊列中,由調度者調用。*/
queueWatcher(this)
}
}
如果你看過響應式原理的時候,在 Watcher 中會有一個 update 函數用來更新視圖的,當 this.sync 為 false 的時候,就標志着是異步更新,所以會執行 queueWatcher 函數
/*將一個觀察者對象push進觀察者隊列,在隊列中已經存在相同的id則該觀察者對象將被跳過,除非它是在隊列被刷新時推送*/
export function queueWatcher (watcher: Watcher) {
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 > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) { // 沒有 waiting,則直接執行 nextTick
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
通過 queueWatcher 函數,我們就能看出來了,Watcher 不是立即更新視圖的,而是會放在一個隊列中,此時是 waiting 等待狀態,它會檢查 id 是否重復,如果重復的話,就不會放進隊列中;如果沒有重復才會放入隊列,而且當前 Watcher 是不能刷新的,如果刷新的話,就從隊列中取出,沒有刷新的 Watcher 才會被放入隊列中。如果沒有 waiting 等待狀態了,那么就證明需要進入下一個 tick 了,會執行 nextTick 方法。
nextTick
講了這么多,終於到 nextTick 了
export let isUsingMicroTask = false // 是否使用了微任務
const callbacks = [] /*存放異步執行的回調*/
let pending = false /*一個標記位,如果已經有timerFunc被推送到任務隊列中去則不需要重復推送*/
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// 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 /*一個函數指針,指向函數將被推送到任務隊列中,等到主線程任務執行完時,任務隊列中的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) // 如果是 isIOS 環境,則執行 setTimeout
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && ( // MutationObserver 在 IE 下的兼容性有問題
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 = 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)
}
}
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// 把 cb 加上異常處理存入 callbacks 數組中
callbacks.push(() => {
if (cb) {
try {
// 調用 cb()
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') {
// 返回 promise 對象
return new Promise(resolve => {
_resolve = resolve
})
}
}
nextTick 接收兩個參數,一個是回調函數,一個是當前環境的上下文,執行 nextTick 會將回調函數放入 callbacks 回調隊列中,然后通過 timerFunc 去執行。然后會判斷當前執行環境是否有 Promise,如果有的話,通過 Promise.resolve().then 去執行回調函數中的內容,如果是 IOS 環境的話,則執行 setTimeout,因為 IOS 的某些版本對 Promise 的支持不太好;如果當前環境不支持 Promise,則降級使用微任務 MutationObserver,注釋中也列舉出了很多不支持 Promise 的環境,例如 e.g. PhantomJS, iOS7, Android 4.4;如果 MutationObserver 也不被支持的話,那么就使用宏任務 setImmediate 了;而最壞的情況就是使用 setTimeout 了,至於為什么不直接使用 setTimeout 而多一個 setImmediate,是因為 setImmediate 的執行速度要比 setTimeout,因為 setTimeout 即使將時間參數設為 0 的話,也還是會有 4 ms 的延遲。
為什么要異步更新視圖
<template>
<div>
<div>{{value}}</div>
</div>
</template>
export default {
data () {
return {
value: 0
};
},
mounted () {
for(let i = 0; i < 1000; i++) {
this.value++;
}
}
}
當我們在 mounted 鈎子函數中,循環改變某一個值的時候,如果沒有異步更新,那么 value 每一次 ++ 的時候,都會操作 DOM 去更新,但是這種更新又是沒有意義的,這樣就會非常消耗性能。但是有了異步 DOM 隊列,它只會在下一個 tick 執行,這樣就能保障 i 從 0 直接到 1000 才執行,這樣大大優化了性能。