18 为什么Vue采用异步渲染

Vue 是组件级更新,如果不采用异步更新,那么每次更新数据都会对当前组件进行重新渲染,所以为了性能, Vue 会在本轮数据更新后,在异步更新视图。核心思想 nextTick

源码相关

dep.notify() 通知 watcher进行更新, subs[i].update 依次调用 watcherupdatequeueWatcherwatcher 去重放入队列, nextTickflushSchedulerQueue )在下一tick中刷新watcher队列(异步)

    update () { /* istanbul ignore else */ 
        if (this.lazy) { 
            this.dirty = true 
        } 
        else if (this.sync) { 
            this.run() 
        } 
        else { 
            queueWatcher(this); // 当数据发生变化时会将watcher放到一个队列中批量更新 
        }
    }
    
    export function queueWatcher (watcher: Watcher) { 
        const id = watcher.id // 会对相同的watcher进行过滤 
        if (has[id] == null) { 
            has[id] = true 
            if (!flushing) { 
                queue.push(watcher) 
            } else { 
                let i = queue.length - 1 
                while (i > index && queue[i].id > watcher.id) { 
                    i-- 
                }
                queue.splice(i + 1, 0, watcher) 
            }
            // queue the flush 
            if (!waiting) { 
                waiting = true 
                if (process.env.NODE_ENV !== 'production' && !config.async) { 
                    flushSchedulerQueue() 
                    return 
                }
                nextTick(flushSchedulerQueue) // 调用nextTick方法 批量的进行更新 
            } 
        } 
    }
Last Updated:
Contributors: leeguooooo