vue2从数据变化到视图变化之nextTick使用详解

引言

nextTick在vue中是一个很重要的方法,在new Vue实例化的同步过程中,将一些需要异步处理的函数推到异步队列中去,可以等new Vue所有的同步任务执行完后,再执行异步队列中的函数。

1、vue中nextTick的使用场景

借用vue.js官网中例子:

Vue.component("example", {
  template: "{{ message }}",
  data: function() {
    return {
      message: "未更新"
    };
  },
  methods: {
    updateMessage: function() {
      this.message = "已更新";
      console.log(this.$el.textContent); // => '未更新'
      this.$nextTick(function() {
        console.log(this.$el.textContent); // => '已更新'
      });
    }
  }
});

例子中显示数据变化后直接访问节点内容是'未更新',当使用了this.$nextTick包裹后访问节点内容是'已更新',可以看出如果需要拿到数据变化后的节点,则需要使用this.nextTick,这就是nextTick的使用场景。
那么,$nextTick是从哪里定义的?

2、vue中nextTick在哪里定义

在vue源码initGlobalAPI(Vue)过程中:

import { nextTick } from '../util/index'
// ...
Vue.nextTick = nextTick

3、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
    })
  }
}

(1)callbacks的定义

在nextTick中首先在callbacks中推入进行try {} catch (e) {}捕捉错误的回调函数。

(2)timerFunc的定义

然后,如没有在pengding状态时,将pending置为true,并执行timerFunc函数,这个函数依次根据当前浏览器执行环境中支不支持Promise、MutationObserver和setImmediate方法进行赋值,如果都不支持,则使用setTimeout。

  • 第一步,如果浏览器支持Promise,const p = Promise.resolve(),然后timerFunc中定义p.then(flushCallbacks),通过p.then(flushCallbacks)自执行的能力来诱发flushCallbacks;
  • 第二步,如果浏览器不支持Promise但支持MutationObserver,则其利用DOM属性监听变化的能力,首先定义const observer = new MutationObserver(flushCallbacks),并监听const textNode = document.createTextNode(String(counter))的变化,timerFunc的执行是通过修改textNode值来诱发flushCallbacks的执行。
  • 第三步,以上两者都不满足,但浏览器支持立即执行函数setImmediate,则通过timerFunc = () => { setImmediate(flushCallbacks) }的方式来诱发flushCallbacks.
  • 第四步,以上条件都不满足的时候,则通过timerFunc = () => { setTimeout(flushCallbacks, 0) }将定时器的延迟时间设置为0进行flushCallbacks的诱发。
    以上四步中提到的的flushCallbacks函数,其中pending = false表示同步任务已经执行结束,开始了异步队列的执行。const copies = callbacks.slice(0)进行异步事件的浅拷贝,并将异步队列数组callbacks清空,等待下一次异步队列的推入。通过for (let i = 0; i < copies.length; i++) { copies[i]() }进行当前异步队列中函数的执行。

(3)cb未传入的处理

最后,如果没有传入cb并且环境也支持Promise,return new Promise(resolve => { _resolve = resolve }),然后在执行异步队列中的函数的时候,直接执行_resolve(ctx),为nextTick的使用提供了又一个方法Vue.nextTick().then(function () {// DOM 更新了})。

4、vue中nextTick的任务分类

在timerFunc的定义过程中,Promise和MutationObserver情况下,有一行代码isUsingMicroTask = true表示当前情况使用了微任务。nextTick的实现过程中也用到了宏任务setImmediate和setTimeout。

小结

可以感受到,nextTick异步队列执行是从最优解到次优解的一次降级处理,也是对于异步执行兼容性的处理。

以上就是vue2从数据变化到视图变化之nextTick使用详解的详细内容,更多关于vue2数据视图变化nextTick的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(vue2从数据变化到视图变化之nextTick使用详解)