Vue.nextTick使用和源码分析

Vue.nextTick的应用场景

Vue 是采用异步的方式执行 DOM 更新。只要观察到数据变化,Vue 将开启一个队列,并缓冲同一事件循环中发生的所有数据改变。然后,在下一个的事件循环中,Vue 刷新队列并执行页面渲染工作。所以修改数据后DOM并不会立刻被重新渲染,如果想在数据更新后对页面执行DOM操作,可以在数据变化之后立即使用 Vue.nextTick(callback)。
下面这一段摘自vue官方文档,关于JS 运行机制的说明:

JS 执行是单线程的,它是基于事件循环的。事件循环大致分为以下几个步骤:

(1)所有同步任务都在主线程上执行,形成一个执行栈(execution context stack)。

(2)主线程之外,还存在一个”任务队列”(task queue)。只要异步任务有了运行结果,就在”任务队列”之中放置一个事件。

(3)一旦”执行栈”中的所有同步任务执行完毕,系统就会读取”任务队列”,看看里面有哪些事件。那些对应的异步任务,于是结束等待状态,进入执行栈,开始执行。

(4)主线程不断重复上面的第三步。

在主线程中执行修改数据这一同步任务,DOM的渲染事件就会被放到“任务队列”中,当“执行栈”中同步任务执行完毕,本次事件循环结束,系统才会读取并执行“任务队列”中的页面渲染事件。而Vue.nextTick中的回调函数则会在页面渲染后才执行。
例子如下:

<template>
  <div>
    <div ref="test">{{test}}</div>
  </div>
</template>
// Some code...
data () {
    return {
        test: 'begin'
    };
},
// Some code...
this.test = 'end';
console.log(this.$refs.test.innerText);//"begin"
this.nextTick(() => {
    console.log(this.$refs.test.innerText) //"end"
})

Vue.nextTick实现原理

Vue.nextTick的源码vue项目/src/core/util/路径下的next-tick.js文件,文章最后也会贴出完整的源码
我们先来看看对于异步调用函数的实现方法:

let timerFunc
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)
  }
}

这段代码首先的检测运行环境的支持情况,使用不同的异步方法。优先级依次是Promise、MutationObserver、setImmediate和setTimeout。这是根据运行效率来做优先级处理,有兴趣可以去了解一下这几种方法的差异。总的来说,Event Loop分为宏任务以及微任务,宏任务耗费的时间是大于微任务的,所以优先使用微任务。例如Promise属于微任务,而setTimeout就属于宏任务。最终timerFunc则是我们调用nextTick函数时要内部会调用的主要方法,那么flushCallbacks又是什么呢,我们在看看flushCallbacks函数:

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

这个函数比较简单,就是依次调用callbacks数组里面的方法。还使用slice()方法复制callbacks数组并把callbacks数组清空,这里的callbacks数组就是存放主线程执行过程中的Vue.nextTick()函数所传的回调函数集合(主线程可能会多次使用Vue.nextTick()方法)。到这里就已经实现了根据环境选择异步方法,并在异步方法中依次调用传入Vue.nextTick()方法的回调函数。nextTick函数主要就是要将callback函数存在数组callbacks中,并调用timerFunc方法:

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

可以看到可以传入第二个参数作为回调函数的this。另外如果参数一的条件判断为false时则返回一个Promise对象。例如

Vue.nextTick(null, {value: 'test'})
  .then((data) => {
    console.log(data.value)   // 'test'
  })

这里还使用了一个优化技巧,用pending来标记异步任务是否被调用,也就是说在同一个tick内只调用一次timerFunc函数,这样就不会开启多个异步任务。

完整的源码:

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.
  // Techinically 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
    })
  }
}
    原文作者:toln
    原文地址: https://segmentfault.com/a/1190000019770773
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞