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
的主要應用的場景及原因:
1、在Vue生命周期的created()
鈎子函數進行的DOM操作一定要放在Vue.nextTick()
的回調函數中。
因為在created()
鈎子函數執行的時候 DOM 其實並未進行任何渲染,而此時進行DOM操作無異於徒勞,所以此處一定要將DOM操作的js代碼放進Vue.nextTick()
的回調函數中。與之對應的就是mounted()
鈎子函數,因為該鈎子函數執行時所有的DOM掛載和渲染都已完成,此時在該鈎子函數中進行任何DOM操作都不會有問題 。
2、在數據變化后要執行的某個操作,而這個操作需要使用隨數據改變而改變的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
對象。
源碼
export const nextTick = (function () { const callbacks = [] let pending = false let timerFunc function nextTickHandler () { pending = false; /* 之所以要slice復制一份出來是因為有的cb執行過程中又會往callbacks中加入內容,比如$nextTick的回調函數里又有$nextTick, 那么這些應該放入到下一個輪次的nextTick去執行,所以拷貝一份,遍歷完成即可,防止一直循環下去。 */
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 */
/* nextTick行為利用了microtask隊列, 先使用 Promise.resolve().then(nextTickHandler)來將異步回調 放入到microtask中,Promise 和 MutationObserver都可以使用,但是 MutationObserver 在IOS9.3以上的 WebView中有bug,因此如果滿足第一項的話就可以執行,如果沒有原生Promise就用 MutationObserver。 */
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 (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
/* 創建一個MutationObserver,observe監聽到DOM改動之后執行的回調 nextTickHandler */
var counter = 1
var observer = new MutationObserver(nextTickHandler) var textNode = document.createTextNode(String(counter)); // 使用MutationObserver的接口,監聽文本節點的字符內容
observer.observe(textNode, { characterData: true }); /* 每次執行timerFunc函數都會讓文本節點的內容在0/1之間切換,切換之后將新賦值到那個我們MutationObserver監聽的文本節點上去。 */ timerFunc = () => { counter = (counter + 1) % 2 textNode.data = String(counter) } } else { // fallback to setTimeout
/* 如果上面的兩種都不支持的話,我們就使用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) } }); /* 如果pending為true,表明本輪事件循環中已經執行過 timerFunc(nextTickHandler, 0) */
if (!pending) { pending = true timerFunc() } if (!cb && typeof Promise !== 'undefined') { return new Promise((resolve, reject) => { _resolve = resolve }) } } })()
首先,先了解nextTick
中定義的三個重要變量。
callbacks:
用來存儲所有需要執行的回調函數
pending:
用來標志是否正在執行回調函數
timerFunc:
用來觸發執行回調函數
var callbacks = []; // 緩存函數的數組
var pending = false; // 是否正在執行
var timerFunc; // 保存着要執行的函數
接下來,了解nextTickHandler()
函數。
function nextTickHandler () { pending = false; // 拷貝出函數數組副本
var copies = callbacks.slice(0); // 把函數數組清空
callbacks.length = 0; // 依次執行函數
for (var i = 0; i < copies.length; i++) { copies[i](); } }
這個函數就是$nextTick內實際調用的函數。
接下來,是vue分了三種情況來延遲調用以上這個函數,因為$nextTick目的就是把傳進來的函數延遲到dom更新后再使用,所以這里依次優雅降序的使用js的方法來做到這一點。
1、先判斷是否原生支持promise,如果支持,則利用promise來觸發執行回調函數;
if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); if (isIOS) { setTimeout(noop); } }; }
如果瀏覽器支持Promise,那么就用Promise.then的方式來延遲函數調用,Promise.then方法可以將函數延遲到當前函數調用棧最末端,也就是函數調用棧最后調用該函數。從而做到延遲。
2、否則,如果支持MutationObserver,則實例化一個觀察者對象,觀察文本節點發生變化時,觸發執行所有回調函數。
else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || MutationObserver.toString() === '[object MutationObserverConstructor]' )) { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; }
MutationObserver是h5新加的一個功能,其功能是監聽dom節點的變動,在所有dom變動完成后,執行回調函數。
具體有以下幾點變動的監聽
- childList:子元素的變動
- attributes:屬性的變動
- characterData:節點內容或節點文本的變動
- subtree:所有下屬節點(包括子節點和子節點的子節點)的變動
可以看出,以上代碼是創建了一個文本節點,來改變文本節點的內容來觸發的變動,因為我們在數據模型更新后,將會引起dom節點重新渲染,所以,我們加了這樣一個變動監聽,用一個文本節點的變動觸發監聽,等所有dom渲染完后,執行函數,達到我們延遲的效果。
3、如果都不支持,則利用setTimeout設置延時為0
else { timerFunc = function () { setTimeout(nextTickHandler, 0); }; }
利用setTimeout的延遲原理,setTimeout(func, 0)會將func函數延遲到下一次函數調用棧的開始,也就是當前函數執行完畢后再執行該函數,因此完成了延遲功能。
最后是queueNextTick
函數。因為nextTick
是一個即時函數,所以queueNextTick
函數是返回的函數,接受用戶傳入的參數,用來往callbacks里存入回調函數。
return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { cb.call(ctx); } if (_resolve) { _resolve(ctx); } }); // 如果沒有函數隊列在執行才執行
if (!pending) { pending = true; timerFunc(); } // promise化
if (!cb && typeof Promise !== 'undefined') { console.log('進來了') return new Promise(function (resolve) { _resolve = resolve; }) } }
這個return的函數就是我們實際使用的閉包函數,每一次添加函數,都會想callbacks這個函數數組入棧。然后監聽當前是否正在執行,如果沒有,執行函數。這個很好理解。下面一個if是promise化。
this.$nextTick(function () { }) // promise化
this.$nextTick().then(function () { }.bind(this))
以上代碼中第二種寫法我們不常見把,直接調用$nextTick函數然后用promise格式去書寫代碼,不過這個then里面需要手動綁定this,vue內部沒有給做處理。