Vue 源码学习之异步更新 nextTick

从平常的开发中,我们可以得知 Vue 更新 DOM 是异步执行的,也就是当数据发生变化时,Vue 内部会开启一个异步更新队列,将更新的数据推入队列,待队列中所有数据变化完成之后,视图再统一进行更新;

在前面的学习中,我们知道 Watcher类在执行 update时,会调用 queueWatcher,它的作用就是 watcher更新时将他们缓存起来,之后数据完成更新之后再一起调用,为什么要这么做呢?试想一下,每次改变数据都会触发相应的 watcher更新,这也意味着每改变一次就渲染一次,这样会很耗费性能,不是我们想要的结果,为了解决这种场景,异步更新诞生了;

// src/core/observer/scheduler.js

function flushSchedulerQueue () {
    
    
    currentFlushTimestamp = getNow()
    // 标识位置为真,代表当前正在进行队列调度
    flushing = true
    let watcher, id

    // 在刷新前对队列进行排序, 它可以确保:
    // 1. 组件从父组件更新到子组件
    // 2. 组件的用户 watcher 在它的渲染 watcher 之前运行
    // 3. 如果一个组件在父组件的监视程序运行期间被销毁,则可以跳过
    queue.sort((a, b) => a.id - b.id)

    // 遍历循环调用 watcher 的 run 方法,执行真正的更新操作
    for (index = 0; index < queue.length; index++) {
    
    
        watcher = queue[index]
        if (watcher.before) {
    
    
            watcher.before()
        }
        id = watcher.id
        has[id] = null
        watcher.run()
        // 无限循环更新判断
        if (process.env.NODE_ENV !== 'production' && has[id] != null) {
    
    
            circular[id] = (circular[id] || 0) + 1
            if (circular[id] > MAX_UPDATE_COUNT) {
    
    
                warn(
                    'You may have an infinite update loop ' + (
                        watcher.user
                        ? `in watcher with expression "${
      
      watcher.expression}"`
                        : `in a component render function.`
                    ),
                    watcher.vm
                )
                break
            }
        }
    }

    // 在重置状态之前,保留队列的副本
    const activatedQueue = activatedChildren.slice()
    const updatedQueue = queue.slice()

    // 重置,清空队列
    resetSchedulerState()

    // 调用更新和激活的钩子
    callActivatedHooks(activatedQueue)
    callUpdatedHooks(updatedQueue)

    if (devtools && config.devtools) {
    
    
        devtools.emit('flush')
    }
}

export function queueWatcher (watcher: Watcher) {
    
    
    const id = watcher.id
    // 去重
    if (has[id] == null) {
    
    
        has[id] = true
        if (!flushing) {
    
    
            // 将同步代码推到队列里面
            queue.push(watcher)
        } else {
    
    
            // 如果当前是 flushing 状态,则根据 watcher 的 id 拼接到队列里面
            let i = queue.length - 1
            while (i > index && queue[i].id > watcher.id) {
    
    
                i--
            }
            queue.splice(i + 1, 0, watcher)
        }
        if (!waiting) {
    
    
            waiting = true
            if (process.env.NODE_ENV !== 'production' && !config.async) {
    
    
                flushSchedulerQueue()
                return
            }
            // 异步调用
            nextTick(flushSchedulerQueue)
        }
    }
}

queueWatcher方法得知,它是先把同步代码放到更新队列里面去,然后通过 nextTick异步调用执行队列的事件,flushSchedulerQueue是执行队列里面的 watcher,等到队列里面的代码执行完毕后,清空队列;

nextTick 实现原理

// src/core/util/next-tick.js
let timerFunc

// 定义异步方法,优雅降级,依次为 Promise、MutationObserver、setImmediate、setTimeout
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)
    }
}

function flushCallbacks () {
    
    
    pending = false
    // 拷贝回调数组
    const copies = callbacks.slice(0)
    // 清空回调
    callbacks.length = 0
    // 遍历执行回调
    for (let i = 0; i < copies.length; i++) {
    
    
        copies[i]()
    }
}

export function nextTick (cb?: Function, ctx?: Object) {
    
    
    let _resolve
    // 将回调函数 push 到 callbacks 数组
    callbacks.push(() => {
    
    
        if (cb) {
    
    
            try {
    
    
                cb.call(ctx)
            } catch (e) {
    
    
                handleError(e, ctx, 'nextTick')
            }
        } else if (_resolve) {
    
    
            _resolve(ctx)
        }
    })
    // 多次调用 nextTick,只会执行一次,等到 callbacks 清空之后再变为 false
    if (!pending) {
    
    
        pending = true
        timerFunc()
    }
    if (!cb && typeof Promise !== 'undefined') {
    
    
        return new Promise(resolve => {
    
    
            _resolve = resolve
        })
    }
}

nextTick主要把回调函数存到 callbacks数组等待执行,利用 PromiseMutationObserversetImmediatesetTimeout进行优雅降级,将执行函数放到微任务或宏任务中,等到事件循环到微任务或宏任务时,依次执行 callbacks里面的执行函数;

总结:

Vue 更新 DOM 是采用异步更新,异步更新的关键是 nextTicknextTick内部主要依靠浏览器 EventLoop实现,采用优雅降级的方式,依次是PromiseMutationObserversetImmediatesetTimeout

猜你喜欢

转载自blog.csdn.net/Ljwen_/article/details/124753256