vue.$nextTick原理

51 阅读3分钟

nextTick:官方文档的解释是可以在DOM更新完毕之后执行一个回调;可以看作是在下次DOM更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新之后的DOM

尽管MVVM框架并不推荐访问DOM,但有时会有操作DOM的需求,尤其是在和第三方组件配合时,免不了要进行DOM操作,而nextTick提供了一个桥梁,确保操作的是更新后的DOM

Vue如何检测到DOM更新完毕呢?

有个H5新增属性:MutationObserver 可以监听到DOM节点的改动

//MutationObserver基本用法

var observer = new MutationObserver(function(){
//这里是回调函数
 console.log("DOM发生了变化")
})
var article = document.querySelector("article")
observer.observer(article)

Vue中关于nextTick的源码

/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

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]()
  }
}

// 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)
  }
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

对是否支持Promise进行一个兼容判断,根本上是一个回调函数

for(let i =0;i<100;i++){
    dom.style.left=i+"px"
}

上边的100次for循环同属于一个任务,浏览器只在该任务执行完毕之后进行一次DOM更新。

vue的数据响应过程:数据更改->通知Watcher->更新DOM.

Microtask

从名字看,可以称为微任务

每一次事件循环都包含一个微任务队列,在循环结束后会依次执行队列中的microtask并且移除,然后在开始下一次事件循环。这种方法和setTimeout类似,

在执行微任务的过程中加入微任务队列的微任务,也会在下一次事件循环之前被执行。也就是说宏任务要在微任务执行完成之后才能执行。Vue进行DOM更新内部也是调用nextTick来做异步队列控制。当我们自己调用nextTick时,它就在更新DOM的那个微任务后追加了我们自己的回调函数,从而确保了我们的代码在DOM更新后执行。

最优的微任务队列就是Promise,但是Promise是ES6新增属性,对于一些老的浏览器这种就存在bug(某些老公司会坚持使用老IE浏览器,即使IE没有了),所以代码中就存在如果判断不支持Promise的判断,如果有这种情况,就开始从微任务降级为宏任务。

但是setTimeout不是最佳方案,因为setTimeout有着4ms的延迟,着是不可避免的。

最佳方案依次是:setimmediate、messageChannel、setTimeout。

setimmediate算是最理想的解决方案了,但是有兼容问题,IE和nodejs支持

MessageChannel的onmessage回调也是microtask,但是也有兼容性问题,所以只能是setTimeout来兜底。

总结

以上是Vue的nextTick方法的实现原理,大体是:

1.Vue用异步队列的方法来控制DOM更新和nextTick回调先后执行

2.microtask因为高优先级特性,能确保队列中的微任务在循环前执行完毕

3.因为兼容问题,不得不向下兼容,从微任务向宏任务兼容降级