# $nextTick原理

Vue.$nextTick内部调用的是nextTick (opens new window)方法,该方法是在initGlobalAPI (opens new window)时,给Vue添加的全局方法。主要是利用了浏览器的EventLoop。关于浏览器的EventLoop,可参考这篇文章 (opens new window)。
整个nextTick的过程比较如下,不清楚的可参考代码中的注释。

  1. 创建一个timerFunc:
    1. timerFunc会根据浏览器的支持情况,依次选择Promise.then -> MutationObserver -> setImmediate -> setTimeout。
    2. 当我们通过nextTick(cb)调用时,将cb放入callbacks数组中。并在下一个tick中,依次执行callbacks数组中的方法。执行完成后,清空数组,并恢复pending的状态。
    3. 同时将pending置为true,这样,后续再调用nextTick时,只会将cb放入数组中。这样可以保证,我们只会启动一个任务(微任务或宏任务)。
const callbacks = []
let pending = false
// 清空callback数组,并将pending设置为false
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}
// 定义一个异步任务timerFunc
let timerFunc
if (typeof Promise !== 'undefined') {
  // 如果支持Promise
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
  }
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  // 如果支持MutationObserver
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {  // 修改文本节点数据,执行flushCallbacks
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // 如果支持setImmediate
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // 都不支持,采用setTimeout
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  // 将cb放入callback数组
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  // 默认pending为fales,第一次执行nextTick时,置为true,并执行timerFunc(它会在下一个tick中执行callbacks中的方法)
  // 后续再执行nextTick时,只需要将cb放入数组即可
  if (!pending) {
    pending = true
    timerFunc();
  }
  // 为了nextTick支持Promise的写法
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
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