在使用 vue 的过程中,如果碰到需要将更新的数据渲染到DOM上才进行后续操作的话,会用到$nextTick。用法如下:
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
 1
2
3
4
5
6
7
8
9
10
11
12 // 修改数据
vm.msg = 'Hello'
// DOM 还没有更新
Vue.nextTick(function () {
// DOM 更新了
})
// 作为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示)
Vue.nextTick()
.then(function () {
// DOM 更新了
})
也就是说,回调函数将会在下次 DOM 更新循环结束后调用。
那 DOM 更新循环是什么? 下次更新循环呢?
我们知道 Vue 是异步更新代码的,异步更新是就是每次属性修改会将更新操作先放入一个队列中,当所有的更新操作完成后,会一次性执行队列中所有的更新方法,同时清空队列。如果是同步更新,就会在每次属性变化的时候去渲染DOM,如果修改两个属性,就会渲染两次,这样的性能开销是非常大的。
在深入理解 nextTick 之前,先了解一下JS运行机制。
分析 Vue 的 nextTick 源码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// v2.6.6  src/core/util/next-tick.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 = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  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 = () => {
    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.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.
  // Techinically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}
export function nextTick (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()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
可以看到 nextTick 是用 Promise 实现的,也就是说是放入 microtask 中的,为什么不放入 macrotask 用 setTimeout 呢?
如果放入 macrotask 中,则会在当前脚本执行完后清空一次 microtask,然后执行 render 渲染页面,此时还未执行更新操作,因为更新操作在下一轮事件循环中的 macrotask,所以此时 DOM 并未修改,如果要渲染成功就需要两次事件循环。所以异步更新 DOM 操作要放到 microtask 中。尽可能的用 microtask,如果浏览器不支持,再用 macrotask。
1  | if (typeof Promise !== 'undefined' && isNative(Promise)) {  | 
- 当浏览器支持 Promise,使用 Promise 触发回调。
 - 否则,如果支持 MutationObserver,实例化观察者对象。
 - 否则,如果支持 setImmediate,则用 setImmediate。
 - 最后,如果都不支持,使用 setTimeout 0。
 
不管哪种任务,最终都赋值给 一个异步延迟的函数 timerFunc。
再接着看 nextTick 函数,它接收两个参数,第一个参数是回调函数 cb,第二个参数是当前环境上下文 ctx。将回调函数 cb 添加到 callbacks 数组中,此时回调函数并没有执行,当pending 为 false 时,开始执行。pending 在最开始文件首部定义let pending = false,它是一个标识,也就是锁,表示队列中是否有在等待调用的回调,当没有时,执行 timerFunc。执行时完后将 pending 恢复为 false(打开状态)。
1  | export function nextTick (cb?: Function, ctx?: Object) {  | 
timerFunc 里注册了回调事件 flushCallbacks,当调用栈执行完毕后再去执行里面的 flushCallbacks 事件,flushCallbacks 内部在执行 callbacks 回调时对回调函数队列做了一个备份,因为如果出现 nextTick 回调里又有 nextTick,那从设计角度看,内层nextTick应该放入新的 microtask 中,避免外层的 nextTick 回调函数和内层的 nextTick 回调函数在同一个 microtask 中被执行。1
2
3
4
5
6
7
8
9
10
11
12function flushCallbacks () {
  pending = false
  // 拷贝一份,防止出现cb回调函数执行时又往callback中添加回调
  // 比方说nextTick的回调里又有nextTick,内层nextTick应该放入新的microtask中
  // 拷贝一份执行完当前的即可
  const copies = callbacks.slice(0)
  // 拷贝完将callbacks清空
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}
所以,精简一下nextTick核心代码如下。(setTimeout 来模拟异步执行回调)
1  | let callbacks = [];  |