介绍
nextTick
是Vue
的一个核心功能,在很多场景下我们设置了data
上的数据后,需要访问Dom
,如果直接访问是不行的,因为Vue
的页面渲染更新是异步的,下面我们通过源码来看一下其中的奥秘。
源码
Vue版本 2.6.14
nextTick
方法的代码位置在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
})
}
}
nextTick
将我们的回调放到了callbacks
中,然后pending = false
时执行timerFunc
方法,我们来看一下timerFunc
的实现:
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]()
}
}
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) ||
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)
}
}
timerFunc
方法就是nextTick
的核心,该方法依次尝试使用Promise
、MutationObserver
、setImmediate
,都不支持的话,就会降级为setTimeout
。通过事件队列的机制,优先使用微任务,不支持再使用宏任务,来实现在当前主js执行完后,再异步去执行nextTick
中的代码逻辑。
总结
通过上面的分析我们了解到数据的变化到 DOM 的重新渲染是一个异步过程,发生在下一个 tick。这就是我们平时在开发的过程中,比如从服务端接口去获取数据的时候,数据做了修改,如果我们的某些方法去依赖了数据修改后的 DOM 变化,我们就必须在 nextTick
后执行。比如下面的伪代码:
getAsyncData().then((res)=>{
this.list = res.data
this.$nextTick(() => {
// 这里我们可以获取变化后的 DOM
})
})