异步更新是 Vue
核心实现之一,在总体流程中充当着 watcher
更新的调度者这一角色。大部分 watcher
更新都会通过它的处理,在适当时机让更新有序的执行。而 nextTick
做为异步更新的核心,也是须要学习的重点。ios
本文你能学习到:数组
在理解异步更新前,须要对JS运行机制有些了解,若是你已经知道这些知识,能够选择跳过这部份内容。promise
JS 执行是单线程的,它是基于事件循环的。事件循环大体分为如下几个步骤:浏览器
“任务队列”中的任务(task)被分为两类,分别是宏任务(macro task)和微任务(micro task)app
宏任务:在一次新的事件循环的过程当中,遇到宏任务时,宏任务将被加入任务队列,但须要等到下一次事件循环才会执行。常见的宏任务有 setTimeout、setImmediate、requestAnimationFrame框架
微任务:当前事件循环的任务队列为空时,微任务队列中的任务就会被依次执行。在执行过程当中,若是遇到微任务,微任务被加入到当前事件循环的微任务队列中。简单来讲,只要有微任务就会继续执行,而不是放到下一个事件循环才执行。常见的微任务有 MutationObserver、Promise.thendom
总的来讲,在事件循环中,微任务会先于宏任务执行。而在微任务执行完后会进入浏览器更新渲染阶段,因此在更新渲染前使用微任务会比宏任务快一些。异步
关于事件循环和浏览器渲染能够看下 晨曦时梦见兮 大佬的文章 《深刻解析你不知道的 EventLoop 和浏览器渲染、帧动画、空闲回调(动图演示)》async
既然异步更新是核心之一,首先要知道它的做用是什么,解决了什么问题。ide
先来看一个很常见的场景:
created(){ this.id = 10 this.list = [] this.info = {} }
总所周知,Vue
基于数据驱动视图,数据更改会触发 setter
函数,通知 watcher
进行更新。若是像上面的状况,是否是表明须要更新3次,并且在实际开发中的更新可不止那么少。更新过程是须要通过繁杂的操做,例如模板编译、dom diff,频繁进行更新的性能固然不好。
Vue
做为一个优秀的框架,固然不会那么“直男”,来多少就照单全收。Vue
内部实际是将 watcher
加入到一个 queue
数组中,最后再触发 queue
中全部 watcher
的 run
方法来更新。而且加入 queue
的过程当中还会对 watcher
进行去重操做,由于在一个组件中 data
内定义的数据都是存储同一个 “渲染watcher
”,因此以上场景中数据即便更新了3次,最终也只会执行一次更新页面的逻辑。
为了达到这种效果,Vue
使用异步更新,等待全部数据同步修改完成后,再去执行更新逻辑。
异步更新内部是最重要的就是 nextTick
方法,它负责将异步任务加入队列和执行异步任务。Vue
也将它暴露出来提供给用户使用。在数据修改完成后,当即获取相关DOM还没那么快更新,使用 nextTick
即可以解决这一问题。
官方文档对它的描述:
在下次 DOM 更新循环结束以后执行延迟回调。在修改数据以后当即使用这个方法,获取更新后的 DOM。
// 修改数据 vm.msg = 'Hello' // DOM 尚未更新 Vue.nextTick(function () { // DOM 更新了 }) // 做为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示) Vue.nextTick() .then(function () { // DOM 更新了 })
nextTick
使用方法有回调和Promise两种,以上是经过构造函数调用的形式,更常见的是在实例调用 this.$nextTick
。它们都是同一个方法。
在 Vue
源码 2.5+ 后,nextTick
的实现单独有一个 JS 文件来维护它,它的源码并不复杂,代码实现不过100行,稍微花点时间就能啃下来。源码位置在 src/core/util/next-tick.js
,接下来咱们来看一下它的实现,先从入口函数开始:
export function nextTick (cb?: Function, ctx?: Object) { let _resolve // 1 callbacks.push(() => { if (cb) { try { cb.call(ctx) } catch (e) { handleError(e, ctx, 'nextTick') } } else if (_resolve) { _resolve(ctx) } }) // 2 if (!pending) { pending = true timerFunc() } // $flow-disable-line // 3 if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve }) } }
cb
即传入的回调,它被 push
进一个 callbacks
数组,等待调用。pending
的做用就是一个锁,防止后续的 nextTick
重复执行 timerFunc
。timerFunc
内部建立会一个微任务或宏任务,等待全部的 nextTick
同步执行完成后,再去执行 callbacks
内的回调。Promise
形式,返回一个 Promise
,_resolve
被调用时进入到 then
。继续往下走看看 timerFunc
的实现:
// 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.x MutationObserver.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 = 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)) { // 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) } }
上面的代码并不复杂,主要经过一些兼容判断来建立合适的 timerFunc
,最优先确定是微任务,其次再到宏任务。优先级为 promise.then
> MutationObserver
> setImmediate
> setTimeout
。(源码中的英文说明也很重要,它们能帮助咱们理解设计的意义)
咱们会发现不管哪一种状况建立的 timerFunc
,最终都会执行一个 flushCallbacks
的函数。
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]() } }
flushCallbacks
里作的事情 so easy,它负责执行 callbacks
里的回调。
好了,nextTick
的源码就那么多,如今已经知道它的实现,下面再结合异步更新流程,让咱们对它更充分的理解吧。
数据被改变时,触发 watcher.update
// 源码位置:src/core/observer/watcher.js update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) // this 为当前的实例 watcher } }
调用 queueWatcher
,将 watcher
加入队列
// 源码位置:src/core/observer/scheduler.js const queue = [] let has = {} let waiting = false let flushing = false let index = 0 export function queueWatcher (watcher: Watcher) { const id = watcher.id // 1 if (has[id] == null) { has[id] = true // 2 if (!flushing) { queue.push(watcher) } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. let i = queue.length - 1 while (i > index && queue[i].id > watcher.id) { i-- } queue.splice(i + 1, 0, watcher) } // queue the flush // 3 if (!waiting) { waiting = true nextTick(flushSchedulerQueue) } } }
watcher
都有本身的 id
,当 has
没有记录到对应的 watcher
,即第一次进入逻辑,不然是重复的 watcher
, 则不会进入。这一步就是实现 watcher
去重的点。watcher
加入到队列中,等待执行waiting
的做用是防止 nextTick
重复执行flushSchedulerQueue
做为回调传入 nextTick
异步执行。
function flushSchedulerQueue () { currentFlushTimestamp = getNow() flushing = true let watcher, id // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort((a, b) => a.id - b.id) // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index] if (watcher.before) { watcher.before() } id = watcher.id has[id] = null watcher.run() } // keep copies of post queues before resetting state const activatedQueue = activatedChildren.slice() const updatedQueue = queue.slice() resetSchedulerState() // call component updated and activated hooks callActivatedHooks(activatedQueue) callUpdatedHooks(updatedQueue) }
flushSchedulerQueue
内将刚刚加入 queue
的 watcher
逐个 run
更新。resetSchedulerState
重置状态,等待下一轮的异步更新。
function resetSchedulerState () { index = queue.length = activatedChildren.length = 0 has = {} if (process.env.NODE_ENV !== 'production') { circular = {} } waiting = flushing = false }
要注意此时 flushSchedulerQueue
还未执行,它只是做为回调传入而已。由于用户可能也会调用 nextTick
方法。这种状况下,callbacks
里的内容为 ["flushSchedulerQueue", "用户的nextTick回调"],当全部同步任务执行完成,才开始执行 callbacks
里面的回调。
因而可知,最早执行的是页面更新的逻辑,其次再到用户的 nextTick
回调执行。这也是为何咱们能在 nextTick
中获取到更新后DOM的缘由。
异步更新机制使用微任务或宏任务,基于事件循环运行,在 Vue
中对性能起着相当重要的做用,它对重复冗余的 watcher
进行过滤。而 nextTick
根据不一样的环境,使用优先级最高的异步任务。这样作的好处是等待全部的状态同步更新完毕后,再一次性渲染页面。用户建立的 nextTick
运行页面更新以后,所以可以获取更新后的DOM。
往期 Vue 源码相关文章: