vue
在更新DOM
时是异步的,所以在数据变更后要对DOM进行操作时往往会出现问题,虽然这种操作在vue开发中是极力避免并且使用场景很少,但是某些特殊情况下是需要支持的, Vue.nextTick
API是专门为这种特殊情况而设计的。
# 1. 异步更新队列
Vue
在更新 DOM 时是异步执行的。只要侦听到数据变化,Vue
将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环“tick”
中,Vue
刷新队列并执行实际 (已去重的) 工作。
简单来说,当我们设置vm.message = 'new message'
,组件不会立即重新渲染。当刷新队列时,组件会在下一个事件循环“tick”中更新。假如我们在给vm.message重新赋值后需要对更新后的DOM进行操作,这时候获取不到更新后的DOM,因为DOM更新是异步的。为了处理这种情况,vue提供了 Vue.nextTick([callback, context]
API,该API有两个参数,第一个参数是回调函数,该回调函数会在DOM渲染完成之后调用,在这里你可以对更新后的DOM进行操作。第二个参数是可选参数,默认为当前执行上下文的vue对象。在2.1.0版本之后,Vue.nextTick在没有回调且在支持Promise
的环境中,会返回一个Promise
,使用时注意兼容问题。
# 2. Vue.nextTick
使用
Vue.nextTick
使用方法这里贴个官方文档的例子吧。
<div id="example">{{message}}</div>
var vm = new Vue({
el: '##example',
data: {
message: '123'
}
})
vm.message = 'new message' // 更改数据
vm.$el.textContent === 'new message' // false
Vue.nextTick(function () {
vm.$el.textContent === 'new message' // true
})
2
3
4
5
6
7
8
9
10
11
12
13
在组件内部使用vm.$nextTick()
时不需要全局Vue
,而且回调函数中的this
会自动绑定到当前的Vue
实例上,可以使用this.$nextTick(() => {})
的方式调用。 由于$nextTick
返回一个Promise
对象,所以也可以使用async/await
语法。
# 3. Vue.nextTick
源码分析
# 3.1. web平台实现
那么,Vue.nextTick
是如何实现的呢?带着这个疑问,我查阅了Vue
内部实现该API的源码。这部分源码很有借鉴意义,值得我们学习。 本文Vue.nextTick
源码是基于2.6.10版本,web平台的实现在较早的版本中使用了MutationObserver
的方式,2.6.10版本尝试使用Promise
.then
、MutationObserver
和setImmediate
,以上方式都不支持时使用setTimeout(fn, 0)
做最后兼容。在支持weex的版本上使用了MessageChannel
。
首先,在源码src/core/instance/render.js
文件中,Vue
在renderMixin
方法内给Vue对象的原型上挂载了nextTick
方法,向用户暴露除了该API。
import {
warn,
nextTick,
emptyObject,
handleError,
defineReactive
} from '../util/index'
// ....
export function renderMixin (Vue: Class<Component>) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype)
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
Vue.prototype._render = function (): VNode {
// ...
}
}
nextTick方法的实现是在src/core/util/next-tick.js中,
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
export let isUsingMicroTask = false
// 缓存任务回调函数
const callbacks = []
let pending = false
// ...
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()
}
// 下面这段代码是当nextTick不传cb参数时,返回一个Promise的调用
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
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
可以看到,调用nextTick
方法时,如果有cb
参数就把回调函数存入callbacks
数组, 通过flushCallbacks
方法调用和重置,nextTick
方法如果没有cb
参数,就返回一个Promise
。这里我们重点看一下timerFunc
方法的实现,这是nextTick
的核心内容。
// ...
// isUsingMicroTask 该变量缓存是否支持microTask,在 src/platforms/web/runtime/modules/events.js 中有用到
export let isUsingMicroTask = false
const callbacks = []
let pending = false
// 该方法封装了调用nextTick回调并重置callbacks的逻辑
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
flushCallbacks
方法的逻辑还是很简单的,复制一份callbaks
并清空callbaks
,然后遍历调用备份的回调。 接下来是timerFunc
的实现,结合作者留下的大量注释,可以快速理解其内在原理。
// 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)
}
}
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
可以从源码看到,timerFunc
方法根据不同的支持情况会有不同的实现,如果支持Promise
会在Promise.resolve
中处理回调,这里需要注意一下IOS上Promise
的异常问题,源码的注释中有说明,在部分UIWebViews
中,Promise.then
不会完全中断,这时候需要处理一个空计时器来强制刷新microtask
队列,我们摘出来这部分逻辑再看一下:
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)
}
2
3
4
5
6
7
8
9
10
在不支持Promise
时,如果支持MutationObserver
,就会使用MutationObserver
构造函数实例一个监听对象,使用observer.observe
方法监听一个TextNode
,在DOM
刷新时调用flushCallbacks
。
如果MutationObserver
也不支持,则尝试使用node标准接口setImmediate
,因为setImmediate
相比setTimeout
会是一个更好的选择,最后使用setTimeout
兜底。
可以发现,这里综合考虑了各种情况,最先尝试使用支持microtask
的Promise
和MutationObserver
,如果都不支持就使用定时器,由于HTML5规定setTimeout
的最小间隔时间是4ms,所以会在setTimeout(fn,0)
前面尝试使用setImmediate
。
# 3.2. weex平台实现
前面说过,vue在支持跨平台框架weex
中实现Vue.nextTick
使用了消息通道MessageChannel
,简单来说,如果支持Promise
就使用Promise.then
,如果不支持就使用MessageChannel
,最后使用setTimeout
兜底。
/* globals MessageChannel */
var callbacks = [];
var pending = false;
function flushCallbacks () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. ##4521, ##6690) or even between bubbling of the same
// event (##6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. ##6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
var microTimerFunc;
var macroTimerFunc;
var useMacroTask = false;
// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = function () {
setImmediate(flushCallbacks);
};
} else if (typeof MessageChannel !== 'undefined' && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = flushCallbacks;
macroTimerFunc = function () {
port.postMessage(1);
};
} else {
/* istanbul ignore next */
macroTimerFunc = function () {
setTimeout(flushCallbacks, 0);
};
}
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
microTimerFunc = function () {
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); }
};
} else {
// fallback to macro
microTimerFunc = macroTimerFunc;
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a (macro) task instead of a microtask.
*/
function nextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
if (useMacroTask) {
macroTimerFunc();
} else {
microTimerFunc();
}
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
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