异步更新队列-nextTick()
- Vue 更新DOM是异步执行的,批量的
在下次DOM更新循环结束之后执行延迟回调。在吸怪数据之后立即使用此方法,获取更新后的DOM - vm.$nextTick(){/操作dom/} Vue.nextTick(function(){})
vm.$nextTick()代码演示
<div id="app"><p ref="p1">{
{
msg}}</p>
</div>
<script>const vm = new Vue({
el:"#app",data:{
msg:"hello nextTick"},mounted(){
this.msg = "hello world"this.$nextTick(()=>{
console.log(this.$refs.p1.textContent)})}})
</script>
源码解析
位置:src/core/instance/render.js
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)}
源码
- 手动调用vm.$nextTick()
- 在Watcher 的queueWatcher 中执行 nextTick()
- src/core/util-tick.js
/* @flow */
/* globals MutationObserver */import {
noop } from 'shared/util'
import {
handleError } from './error'
import {
isIE, isIOS, isNative } from './env'export let isUsingMicroTask = falseconst callbacks = []
let pending = false// 刷新回调函数的数组
function flushCallbacks () {
pending = falseconst copies = callbacks.slice(0)callbacks.length = 0for (let i = 0; i < copies.length; i++) {
copies[i]()}
}// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */// 处理兼容性
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()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.xMutationObserver.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 = 1const observer = new MutationObserver(flushCallbacks)const textNode = document.createTextNode(String(counter))observer.observe(textNode, {
characterData: true})timerFunc = () => {
counter = (counter + 1) % 2textNode.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)}
}export function nextTick (cb?: Function, ctx?: Object) {
// cb 是可选择的回调函数,ctx的执行的上下文,就是Vue的实例let _resolve // 接收promise返回的resolve// 把 cb 加上异常处理存入 callbacks数组中callbacks.push(() => {
//存放回调的队列if (cb) {
try {
// 调用 cb()cb.call(ctx)} catch (e) {
handleError(e, ctx, 'nextTick')}} else if (_resolve) {
_resolve(ctx)}})if (!pending) {
pending = true// 调用timerFunc()}// $flow-disable-lineif (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve})}
}
调用顺序
- nextTick的核心是timerFunc的处理
- 执行函数时候会先将timerFunc放到callbacks数组中
- 会以微任务方式来处理回调函数,如果浏览器不支持,会降级成宏任务
- 异步执行所有的更新dom操作