Vue中的
nextTick
涉及到Vue中DOM的非同步更新,感覺很有意思,特意瞭解了一下。其中關於nextTick
的原始碼涉及到不少知識,很多不太理解,暫且根據自己的一些感悟介紹下nextTick
。
一、示例
先來一個示例瞭解下關於Vue中的DOM更新以及nextTick
的作用。
模板
<div class="app">
<div ref="msgDiv">{{msg}}</div>
<div v-if="msg1">Message got outside $nextTick: {{msg1}}</div>
<div v-if="msg2">Message got inside $nextTick: {{msg2}}</div>
<div v-if="msg3">Message got outside $nextTick: {{msg3}}</div>
<button @click="changeMsg">
Change the Message
</button>
</div>
複製程式碼
Vue例項
new Vue({
el: '.app',
data: {
msg: 'Hello Vue.',
msg1: '',
msg2: '',
msg3: ''
},
methods: {
changeMsg() {
this.msg = "Hello world."
this.msg1 = this.$refs.msgDiv.innerHTML
this.$nextTick(() => {
this.msg2 = this.$refs.msgDiv.innerHTML
})
this.msg3 = this.$refs.msgDiv.innerHTML
}
}
})
複製程式碼
點選前
點選後
從圖中可以得知:msg1和msg3顯示的內容還是變換之前的,而msg2顯示的內容是變換之後的。其根本原因是因為Vue中DOM更新是非同步的(詳細解釋在後面)。
二、應用場景
下面瞭解下nextTick
的主要應用的場景及原因。
- 在Vue生命週期的
created()
鉤子函式進行的DOM操作一定要放在Vue.nextTick()
的回撥函式中
在created()
鉤子函式執行的時候DOM 其實並未進行任何渲染,而此時進行DOM操作無異於徒勞,所以此處一定要將DOM操作的js程式碼放進Vue.nextTick()
的回撥函式中。與之對應的就是mounted()
鉤子函式,因為該鉤子函式執行時所有的DOM掛載和渲染都已完成,此時在該鉤子函式中進行任何DOM操作都不會有問題 。
- 在資料變化後要執行的某個操作,而這個操作需要使用隨資料改變而改變的DOM結構的時候,這個操作都應該放進
Vue.nextTick()
的回撥函式中。
具體原因在Vue的官方文件中詳細解釋:
Vue 非同步執行 DOM 更新。只要觀察到資料變化,Vue 將開啟一個佇列,並緩衝在同一事件迴圈中發生的所有資料改變。如果同一個 watcher 被多次觸發,只會被推入到佇列中一次。這種在緩衝時去除重複資料對於避免不必要的計算和 DOM 操作上非常重要。然後,在下一個的事件迴圈“tick”中,Vue 重新整理佇列並執行實際 (已去重的) 工作。Vue 在內部嘗試對非同步佇列使用原生的
Promise.then
和MessageChannel
,如果執行環境不支援,會採用setTimeout(fn, 0)
代替。
例如,當你設定
vm.someData = 'new value'
,該元件不會立即重新渲染。當重新整理佇列時,元件會在事件迴圈佇列清空時的下一個“tick”更新。多數情況我們不需要關心這個過程,但是如果你想在 DOM 狀態更新後做點什麼,這就可能會有些棘手。雖然 Vue.js 通常鼓勵開發人員沿著“資料驅動”的方式思考,避免直接接觸 DOM,但是有時我們確實要這麼做。為了在資料變化之後等待 Vue 完成更新 DOM ,可以在資料變化之後立即使用Vue.nextTick(callback)
。這樣回撥函式在 DOM 更新完成後就會呼叫。
三、nextTick
原始碼淺析
作用
Vue.nextTick
用於延遲執行一段程式碼,它接受2個引數(回撥函式和執行回撥函式的上下文環境),如果沒有提供回撥函式,那麼將返回promise
物件。
原始碼
/**
* Defer a task to execute it asynchronously.
*/
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]()
}
}
// 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 */
if (typeof Promise !== 'undefined' && isNative(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 (!isIE && 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, iOS7, Android 4.4
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 */
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()
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise((resolve, reject) => {
_resolve = resolve
})
}
}
})()
複製程式碼
首先,先了解nextTick
中定義的三個重要變數。
callbacks
用來儲存所有需要執行的回撥函式
pending
用來標誌是否正在執行回撥函式
timerFunc
用來觸發執行回撥函式
接下來,瞭解nextTickHandler()
函式。
function nextTickHandler () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
複製程式碼
這個函式用來執行callbacks
裡儲存的所有回撥函式。
接下來是將觸發方式賦值給timerFunc
。
- 先判斷是否原生支援promise,如果支援,則利用promise來觸發執行回撥函式;
- 否則,如果支援MutationObserver,則例項化一個觀察者物件,觀察文字節點發生變化時,觸發執行所有回撥函式。
- 如果都不支援,則利用setTimeout設定延時為0。
最後是queueNextTick
函式。因為nextTick
是一個即時函式,所以queueNextTick
函式是返回的函式,接受使用者傳入的引數,用來往callbacks裡存入回撥函式。
timeFunc()
,該函式起到延遲執行的作用。
從上面的介紹,可以得知timeFunc()
一共有三種實現方式。
Promise
MutationObserver
setTimeout
其中Promise
和setTimeout
很好理解,是一個非同步任務,會在同步任務以及更新DOM的非同步任務之後回撥具體函式。
下面著重介紹一下MutationObserver
。
MutationObserver
是HTML5中的新API,是個用來監視DOM變動的介面。他能監聽一個DOM物件上發生的子節點刪除、屬性修改、文字內容修改等等。
呼叫過程很簡單,但是有點不太尋常:你需要先給他綁回撥:
var mo = new MutationObserver(callback)
複製程式碼
通過給MutationObserver
的建構函式傳入一個回撥,能得到一個MutationObserver
例項,這個回撥就會在MutationObserver
例項監聽到變動時觸發。
這個時候你只是給MutationObserver
例項繫結好了回撥,他具體監聽哪個DOM、監聽節點刪除還是監聽屬性修改,還沒有設定。而呼叫他的observer
方法就可以完成這一步:
var domTarget = 你想要監聽的dom節點
mo.observe(domTarget, {
characterData: true //說明監聽文字內容的修改。
})
複製程式碼
在nextTick
中 MutationObserver
的作用就如上圖所示。在監聽到DOM更新後,呼叫回撥函式。
其實使用 MutationObserver
的原因就是 nextTick
想要一個非同步API,用來在當前的同步程式碼執行完畢後,執行我想執行的非同步回撥,包括Promise
和 setTimeout
都是基於這個原因。其中深入還涉及到microtask
等內容,暫時不理解,就不深入介紹了。