Vue中的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.thenMessageChannel,如果執行環境不支持,會采用 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

其中PromisesetTimeout很好理解,是一個異步任務,會在同步任務以及更新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 //說明監聽文本內容的修改。 })

nextTickMutationObserver的作用就如上圖所示。在監聽到DOM更新后,調用回調函數。

 

其實使用 MutationObserver的原因就是 nextTick想要一個異步API,用來在當前的同步代碼執行完畢后,執行我想執行的異步回調,包括PromisesetTimeout都是基於這個原因。其中深入還涉及到microtask等內容,暫時不理解,就不深入介紹了。


原文地址  https://www.jianshu.com/p/a7550c0e164f

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM