VUE的nextTick的使用及原理

nextTick

  • 下面了解下nextTick的主要應(yīng)用的場(chǎng)景及原因。

在Vue生命周期的created()鉤子函數(shù)進(jìn)行的DOM操作一定要放在Vue.nextTick()的回調(diào)函數(shù)中

created()鉤子函數(shù)執(zhí)行的時(shí)候DOM 其實(shí)并未進(jìn)行任何渲染,而此時(shí)進(jìn)行DOM操作無(wú)異于徒勞,所以要將DOM操作的js代碼放進(jìn)Vue.nextTick()的回調(diào)函數(shù)中。與之對(duì)應(yīng)的就是mounted()鉤子函數(shù),因?yàn)樵撱^子函數(shù)執(zhí)行時(shí)所有的DOM掛載和渲染都已完成,此時(shí)在該鉤子函數(shù)中進(jìn)行任何DOM操作都不會(huì)有問(wèn)題 。

在數(shù)據(jù)變化后要執(zhí)行的某個(gè)操作,而這個(gè)操作需要使用隨數(shù)據(jù)改變而改變的DOM結(jié)構(gòu)的時(shí)候,這個(gè)操作都應(yīng)該放進(jìn)Vue.nextTick()的回調(diào)函數(shù)中。
https://zhuanlan.zhihu.com/p/69641232

  • nextTick 按我的理解,就是設(shè)置一個(gè)回調(diào),用于異步執(zhí)行

異步執(zhí)行,比如,就是把你設(shè)置的回調(diào)放在 setTimeout 中執(zhí)行,這樣就算異步了,等待當(dāng)時(shí)同步代碼執(zhí)行完畢再執(zhí)行

但是,每設(shè)置一個(gè) nextTick 就新建一個(gè) setTimeout 又不實(shí)際,

畢竟一個(gè) setTimeout 是異步,兩個(gè)setTimeout 也是異步,兩個(gè)都要等在 同步代碼執(zhí)行完畢之后才執(zhí)行

那我直接只設(shè)置一個(gè) setTimeout 不就好了

  • 那一個(gè) setTimeout 怎么執(zhí)行多個(gè)回調(diào)呢?
    1 存在 回調(diào)數(shù)組 里。每次調(diào)用 nextTick,便往數(shù)組里面 push 設(shè)置的回調(diào)

    2 只注冊(cè)一個(gè) setTimeout,時(shí)間為0,用于遍歷 回調(diào)數(shù)組,然后逐個(gè)執(zhí)行子項(xiàng)

    3 同步代碼執(zhí)行完畢,setTimeout 自然會(huì)執(zhí)行
    Vue 不止使用 setTimeout
    Vue的 nextTick 也是只用setTimeout 嗎,不是的,這里便會(huì)涉及到 javascript 的 宏微任務(wù)

關(guān)于宏微任務(wù),簡(jiǎn)單說(shuō)一下

1 兩者區(qū)別在于執(zhí)行權(quán)重的問(wèn)題,微任務(wù)優(yōu)先級(jí)要比宏任務(wù)高

2 宏任務(wù) 和 微任務(wù) 合作完成一個(gè) Event Loop

3 執(zhí)行一個(gè) 宏任務(wù),便會(huì)執(zhí)行一列微任務(wù)。接著執(zhí)行另一個(gè)宏任務(wù)...(循環(huán)往復(fù),比如一個(gè)setTimeout 就是一個(gè)宏任務(wù))

Vue 2.4 以前,只使用 微任務(wù),因?yàn)槲⑷蝿?wù)執(zhí)行優(yōu)先級(jí)高

Vue 2.5.3 之后,分成了 宏任務(wù) 和 微任務(wù),為了解決連續(xù)事件帶來(lái)的問(wèn)題,比如冒泡(至于為什么,會(huì)有一篇文章說(shuō)明)

Vue 2.6 ,又只使用微任務(wù),因?yàn)橄氲搅似渌k法解決連續(xù)事件的問(wèn)題

Vue 的 宏微任務(wù) 并不算是嚴(yán)格意義上的宏微任務(wù),是種兼容的寫法。

  • Vue 使用了 nextTick 進(jìn)行統(tǒng)一更新
    你應(yīng)該知道,即使在 Vue 中多么頻繁地修改數(shù)據(jù),最后 Vue 頁(yè)面只會(huì)更新一次

這是 Vue 和 nextTick 合作產(chǎn)生的結(jié)果,但又并不只是 nextTick 起作用

比如
數(shù)據(jù) name 被 頁(yè)面引用,name 會(huì)收集到 頁(yè)面的 watcher
name 被修改時(shí),會(huì)通知所有收集到的 watcher 進(jìn)行更新(watcher.update)
this.name = 2
this.name = 3
this.name = 4
name 一時(shí)間被修改三次時(shí),按道理應(yīng)該會(huì)通知三次 watcher 更新,那么頁(yè)面會(huì)更新三次
但是最后只會(huì)更新一次

就是因?yàn)樗麄兊?code>合作

設(shè)置 nextTick 回調(diào) + 過(guò)濾 watcher

當(dāng)數(shù)據(jù)變化后,把 watcher.update 函數(shù)存放進(jìn) nextTick 的 回調(diào)數(shù)組中,并且會(huì)做過(guò)濾。

通過(guò) watcher.id 來(lái)判斷 回調(diào)數(shù)組 中是否已經(jīng)存在這個(gè) watcher 的更新函數(shù)

不存在,才 push

之后 nextTick 遍歷回調(diào)數(shù)組,便會(huì)執(zhí)行了更新

所以
當(dāng)三次修改數(shù)據(jù)的時(shí)候,會(huì)準(zhǔn)備 push進(jìn) 回調(diào)數(shù)組 三個(gè) watcher.update,但是只有第一次是 push 成功的,其他的會(huì)被過(guò)濾掉
所以,不管你修改多少次數(shù)據(jù),nextTick 的回調(diào)數(shù)組中只存在唯一一個(gè) watcher.update,從而頁(yè)面只會(huì)更新一次
源碼

/**
 * 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
      })
    }
  }
})()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容