0%

Vue的$nextTick

先说结论

$nextTick 会尽最大可能较快的在下一次异步任务中执行。

源码追溯

Vue$nextTick 和定义在源码目录的src/core/util/next-tick.js 里面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/core/instance/index.js
// line: 21
renderMixin(Vue)

// renderMixin定义在
// src/core/instance/render.js 里面

export function renderMixin (Vue: Class<Component>) {
...
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
...
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
})
}
}

callbacks 为定义的一个全局数组,用来存放下一次 tick 需要执行的方法,每次执行完成后 callbacks 会清空。

当执行环境支持 promise$nextTick 也支持 promise 化的调用方式。

1
2
3
this.$nextTick().then(() => {
// do something
})

关键的代码在这 4 行

1
2
3
4
if (!pending) {
pending = true
timerFunc()
}

主要功能实现依托于 timerFunc 这是一个根据不同平台有不同的实现。

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
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}

let timerFunc
// 如果支持promise就用promise
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)
}

// 如果不支持promise看看支不支持 MutationObserver
// 关于 MutationObserver, 可以参考https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
} 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)
}

// 如果也不支持MutationObserver看看支不支持setImmediate
} 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)
}
// 如果都不支持至少保证$nextTick为异步的
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}

timerFunc 会依次从 Promise > MutationObserver > setImmediate > setTimeout 这几个中选择一个平台支持的异步来实现。

做这么多,其实就是想让 $nextTick 在下一个异步阶段尽可能的考前执行。

总结

$nextTick 会尽最大可能较快的在下一次异步任务中执行。