前言
以下是使用 vue 的经常使用到 nextTick 的一个场景:
<!--Html-->
<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
})
这个例子是 vue2.x 官方演示案例,许多的开发者都知道这个的用法,但是为什么这样使用就能拿到最新变更后新的 dom 呢?
因此本人带着好奇心翻阅了源码,以此做下记录。
源码分析
首先我们使用 nextTick 的时候,一般都进行了数据变更,比如案例中的:vm.message = 'new message',那从这边一步开始看,数据变更必然触发数据劫持后的 set 方法,并且 notify,以此进入到 notify 方法:
路径:vue/src/core/observer/dep.js
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
notify 方法对数据所依赖的更新函数进行遍历执行,以此进入 update 方法:
路径:vue/src/core/observer/watcher.js
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
update 做了几个判断, 是否 lazy 这个如果是 computed 的话,会设置 dirty,还有是否 sync,这种就直接执行,最后就是我们要说的,vue 更新 state 的时候是异步的,就是因为这里进行了一个队列的收集,而不是变更了 state 数据马上进行更新视图,看看 queueWatcher 做了什么:
路径:
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
将变更后的依赖更新函数,放入到了 queue 中,然后进行了调度,其中看到最后异步,执行了 nextTick(flushSchedulerQueue) 这时候是不是疑惑,难道这个 nextTick 就是我们在代码中所使用的的 vm.nextTick 没错,源码中这里也一样是使用了这个方法,来看看 nextTick 做了什么:
路径:vue/src/core/util/next-tick.js
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
})
}
}
可以看到,它将更新函数传入 push 到了 callbacks 中,并执行了 timeFunc 这是 nextTick 的核心函数:
路径:vue/src/core/util/next-tick.js
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.
// Technically 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)
}
}
看到 timerFunc 就可以明白了,在进行数据变更的时候什么时候进行 dom 的更新,它将更新时间交给了:
- Promise.then
- MutationObserver
- setImmediate
- setTimeout
以上四个机制进行处理,按照以上到下的优先级使用,做了兼容性,前两个是异步微任务,后两个是异步宏任务。
关于微任务和宏任务不了解的可阅读另一篇文章:链接
关于 MutationObserver 的使用可阅读另一篇文章:链接
再次就可了解到,在 vue 更新 state 数据的时候,是进行了批量入队列,然后开启异步任务处理的,所以像:
vm.message = 'new message' // 更改数据
vm.$el.textContent === 'new message' // false
这样变更后马上获取 dom 的 textContent 当然是无法获取到最新的,因为这时候更新 dom 的任务还未开始,因此应该明白以下步骤
vm.message = 'new message' // 更改数据
Vue.nextTick(function () {
vm.$el.textContent === 'new message' // true
})
为什么可以获取到最新 dom 了,因为这时候,同样执行了 nextTick 方法,传入回调开启异步任务,然而这个异步任务,在当前帧中进入队列的异步任务会在当前 event loop 中一同跟随在异步队列后执行,也就是在变更数据后所依赖的更新函数的微任务执行之后紧跟着就会执行代码中写的:
Vue.nextTick(function () {
vm.$el.textContent === 'new message' // true
})
这个任务了,所以这时候可以拿到最新的 dom 数据。