等待下一次 DOM 更新刷新的工具方法。
使用场景
vue中nextTick的使用场景
Vue.component("example", {
template: "<span>{{ message }}</span>",
data: function() {
return {
message: "未更新"
};
},
methods: {
updateMessage: function() {
this.message = "已更新";
console.log(this.$el.textContent); // => '未更新'
this.$nextTick(function() {
console.log(this.$el.textContent); // => '已更新'
});
}
}
});
- nextTick 入参是一个回调函数,这个回调函数就是一个任务
- 每次接受任务nextTick不会立即执行,而是把它push到callbacks这个异步队列里
- 检查pending的值,如果为false,意味着“现在还没有一个异步更新队列被派发出去”, 就调用timerFunc,把当前维护的异步队列派发出去
- 然后调用flushCallbacks异步执行器函数,处理异步任务
源码
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//派发异步任务的函数
//根据不同浏览器,选择不同api来派发异步任务
//当前环境支持 promise
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
//当前环境支持MutationObserver
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// (#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
//当前环境支持setImmediate
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
//当前环境支持 setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {// 全局变量callbacks
if (cb) {
try {
cb.call(ctx)// 这里调用回调
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true// 只执行一次timerFunc函数
timerFunc()
}
// $flow-disable-line
//处理入参不是回调的情况
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}