【轉】簡單理解Vue中的nextTick


前言:

  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實例

  

 1 new Vue({
 2   el: '.app',
 3   data: {
 4     msg: 'Hello Vue.',
 5     msg1: '',
 6     msg2: '',
 7     msg3: ''
 8   },
 9   methods: {
10     changeMsg() {
11       this.msg = "Hello world."
12       this.msg1 = this.$refs.msgDiv.innerHTML
13       this.$nextTick(() => {
14         this.msg2 = this.$refs.msgDiv.innerHTML
15       })
16       this.msg3 = this.$refs.msgDiv.innerHTML
17     }
18   }
19 })

  點擊前

 
  

 

  點擊后

 
  
   從圖中可以得知: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對象。

  源碼

  

 1 /**
 2  * Defer a task to execute it asynchronously.
 3  */
 4 export const nextTick = (function () {
 5   const callbacks = []
 6   let pending = false
 7   let timerFunc
 8 
 9   function nextTickHandler () {
10     pending = false
11     const copies = callbacks.slice(0)
12     callbacks.length = 0
13     for (let i = 0; i < copies.length; i++) {
14       copies[i]()
15     }
16   }
17 
18   // the nextTick behavior leverages the microtask queue, which can be accessed
19   // via either native Promise.then or MutationObserver.
20   // MutationObserver has wider support, however it is seriously bugged in
21   // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
22   // completely stops working after triggering a few times... so, if native
23   // Promise is available, we will use it:
24   /* istanbul ignore if */
25   if (typeof Promise !== 'undefined' && isNative(Promise)) {
26     var p = Promise.resolve()
27     var logError = err => { console.error(err) }
28     timerFunc = () => {
29       p.then(nextTickHandler).catch(logError)
30       // in problematic UIWebViews, Promise.then doesn't completely break, but
31       // it can get stuck in a weird state where callbacks are pushed into the
32       // microtask queue but the queue isn't being flushed, until the browser
33       // needs to do some other work, e.g. handle a timer. Therefore we can
34       // "force" the microtask queue to be flushed by adding an empty timer.
35       if (isIOS) setTimeout(noop)
36     }
37   } else if (!isIE && typeof MutationObserver !== 'undefined' && (
38     isNative(MutationObserver) ||
39     // PhantomJS and iOS 7.x
40     MutationObserver.toString() === '[object MutationObserverConstructor]'
41   )) {
42     // use MutationObserver where native Promise is not available,
43     // e.g. PhantomJS, iOS7, Android 4.4
44     var counter = 1
45     var observer = new MutationObserver(nextTickHandler)
46     var textNode = document.createTextNode(String(counter))
47     observer.observe(textNode, {
48       characterData: true
49     })
50     timerFunc = () => {
51       counter = (counter + 1) % 2
52       textNode.data = String(counter)
53     }
54   } else {
55     // fallback to setTimeout
56     /* istanbul ignore next */
57     timerFunc = () => {
58       setTimeout(nextTickHandler, 0)
59     }
60   }
61 
62   return function queueNextTick (cb?: Function, ctx?: Object) {
63     let _resolve
64     callbacks.push(() => {
65       if (cb) {
66         try {
67           cb.call(ctx)
68         } catch (e) {
69           handleError(e, ctx, 'nextTick')
70         }
71       } else if (_resolve) {
72         _resolve(ctx)
73       }
74     })
75     if (!pending) {
76       pending = true
77       timerFunc()
78     }
79     if (!cb && typeof Promise !== 'undefined') {
80       return new Promise((resolve, reject) => {
81         _resolve = resolve
82       })
83     }
84   }
85 })()

  

  首先,先了解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等內容,暫時不理解,就不深入介紹了。

 


  




免責聲明!

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



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