继 Vue-MVVM 源码解读之后,发现最后调用了 nextTick 方法,现在我们具体看一下 vue 的 nextTick 做了什么
源码目录:src/core/util/next-tick.js
我们在更新数据时,可以使用 VuenextTick 方法直接拿到更新后的值,就是因为 vue 更新 dom 时,使用了 nextTick 方法
我们看一下 next-tick.js 源码做了什么
import { noop } fronextm '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]()
}
}
let timerFunc;
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
if (isIOS) setTimeout(noop);
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
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)) {
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
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()
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
我们可以看到 nextTick 方法里使用了 pedding 变量,这样做就是为了判断当前队列中是否有等待调用的函数,当没有时,执行 timerFunc
timerFunc 在执行前,会通过 if 条件判断
最后调用 flushCallbacks 方法, 循环执行 copies,这个函数做了什么,在 MVVM 章节里说的很清楚,循环调用了 watcher.run 方法,用于 dom 的更新
下一章,会说 vue 如何更新 DOM