Vue源码分析–vm.$nextTick()
Vue
暴露出去的vm.$nextTick()
方法,就是内部的nextTick()
方法,这个方法也为watcher.update()
提供了异步更新的方式。
即通过Watcher
监控的属性
或vm._update()
方法,当其中的子元素变更时,会用nextTick
方法把其回调推入队列。并去重被重复推入的watcher
。然后等待下次事件循环
时,按watcher.id
从小到大依次执行更新
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// 在回调的数组中,推入一个方法
// 如果回调函数cb 存在,则执行回调函数
// 如果cb不存在,且有Promise对象,执行Promise.resolve(ctx)
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
// 如果没有正在执行的回调队列
if (!pending) {
pending = true
// 一个执行回调队列的方法
timerFunc()
}
// 如果cb不存在,且有Promise对象,返回 Promise.resolve(ctx)
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
所以使用方式只有两种
vm.$nextTick(cb)
,回调方法cb
中的this
指向vm
vm.$nextTick().then(vm)
,只有不传cb
时,才能.then()
。而且浏览器必须要支持Promise