Skip to content

nextTick

nextTick是一个开发中经常会用到的一个api,正因为经常使用,所以也是面试高频考点。它的用法最核心的一句话就是将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。 比如从服务端接口去获取数据的时候,数据做了修改,如果我们的某些方法去依赖了数据修改后的 DOM 变化,我们就必须在 nextTick 后执行。比如下面的伪代码:

js
getData(res).then(()=>{
  this.xxx = res.data
  this.$nextTick(() => {
  // 这里可以获取变化后的 DOM
  })
})

官方文档有一句话是Vue在更新dom是异步执行的,这句话非常关键,结合同步任务和异步任务,就是理解nexttick的核心。 接下来来看它的源码实现。

源码分析

nextTick 定义在src/core/util/next-tick.js中,

js
/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

export let isUsingMicroTask = false

const callbacks = []
let pending = false

function flushCallbacks() {
  // 改变pending状态值
  pending = false
  // 备份一个callbacks
  const copies = callbacks.slice(0)
  callbacks.length = 0
  // 依次执行callbacks中的cb
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc

// 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 next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    // promise,下一个tick调用flushCallbacks,
    p.then(flushCallbacks)
    // 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)
  }
  isUsingMicroTask = true

} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  // MutationObserver用来监听dom对象的改变
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  // Use MutationObserver where native Promise is not available,
  // e.g. PhantomJS, iOS7, Android 4.4
  // (#6466 MutationObserver is unreliable in IE11)
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Technically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  // 因为setImmediate会立即执行,而setTimeout至少要4ms后才能执行
  // 但是setImmediate只在ie和node环境中有效
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

export function nextTick(cb?: Function, ctx?: Object) {
  let _resolve
  // 存储回调函数
  callbacks.push(() => {
    // cb是用户传入的,将cb存入callback数组中
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  // 队列是否在被处理中
  if (!pending) {
    pending = true
    // 找到callbacks中所有cb依次调用,异步执行flushCallbacks
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

nexttick就是把要执行的任务推入到一个队列中,在下一个tick中同步执行,数据改变后触发渲染watcher的update。但是watchers的flush是在下一个tick后(flushSchedulerQueue刷新队列更新视图作为nexttick的回调函数),所以重新渲染是异步的,这个flush也是通过微任务和宏任务来控制的。

next-tick.js 声明了一个变量timerfunc,通过依次检测是否支持Promise, MutationObserver 以及setImmediate,三者都不满足的话,则会采用 setTimeout(fn, 0) 代替。 这里暴露的函数nextTick把传入的回调函数 cb 压入 callbacks 数组,最后一次性地调用timerFunc,也就是会在下一个tick执行flushCallbacks,flushCallbacks 就是对 callbacks 遍历,然后执行相应的回调函数。

从数据更新到flushCallback的流程如下: notify-》update-》queueWatcher-》nexttick-》callbacks.push(flushSchedulerQueue) -》timerFunc-》flushCallbacks-》执行 callbacks 中的每一项

异步更新的原因

为什么要异步更新呢? dom数据异步更新,只要侦听到数据变化(notify),在queueWatcher中Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的(这句话!!!非常节省性能)。然后,在下一个的事件循环“tick”中,Vue 刷新flush队列并执行 (已去重的) 工作。

总结

Vue 在更新 DOM 时是异步执行的。只要侦听到数据变化,在queueWatcher中Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环“tick”中,Vue 刷新flush队列并执行实际 (已去重的) 工作。Vue 在内部对异步队列尝试使用原生的 Promise.then、MutationObserver 和 setImmediate,如果执行环境不支持,则会采用 setTimeout(fn, 0) 代替。