对Vue里$nextTick的思考

这个API的官方说明是:

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

这是怎么做的呢?

Vue源码里有一个next-tick.js,源码比较短,我们来仔细看一看:

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

$nextTick实际上是把传入的函数存到一个数组里。然后根据环境情况,添加一个微任务或者宏任务来顺序执行数组里的函数。

代码的注释里写了,之前使用过一次宏任务,结果bug比较多。又换回了微任务。代码来首先使用原生的Promise来添加微任务,如果没有,就使用MutationObserver。如果两个都没有,就降级到宏任务。依次顺序这样的:

添加微任务

Promise

MutationObserver

添加宏任务

setImmediate

setTimeout

 

问题1

微任务和宏任务又啥区别呢?

我在网上找到下面这些图片,对理解又很好的帮助:

蓝色的代表宏任务,黄色的是微任务,灰色的是浏览器重新渲染UI界面。

那么这两个任务的区别就是,在每一次渲染界面之前,都会执行宏任务然后清空微任务队列。为了验证这个过程,可以写下面的代码进行测试。

<template>
  <p id="test">{{ i }}</p>
</template>

<script>
export default {
  data () {
    return {
      i: 1
    }
  },
  components: {
    BookCard
  },
  mounted () {
    const time = new Date().getTime()
    Promise.resolve().then(() => {
      console.log('promise ' + document.querySelector('#test').innerHTML)
      while ((new Date().getTime() - time) < 1000 * 5) {
      }
    })
    this.i = 2
  }
}
</script>

上面代码会输出promise 2,卡住5秒之后,在浏览器里才能看到数字1变成了2。这是因为我们利用Promise在微任务里卡了浏览器5秒,5秒以后浏览器才会重新渲染界面。但是在渲染界面之前,dom节点已经更新了,这是因为在微任务执行的时候,dom节点已经更新完毕了,这里猜测Vue用于更新Dom的操作在这一轮循环的微任务最前面(也就是我们写的Promise.resolve代码之前,Vue应该就插入了一个用于更新Dom的微任务),但是这个时候浏览器还没重新渲染页面。

 

问题2

为什么添加了微任务和宏任务就能在Dom更新以后执行?

根据第一个问题的图片,我们知道,如果在当前任务里添加宏任务。那么下一个循环周期,也就是重新渲染之后会执行(这个时候肯定是Dom更新以后执行的)。

那么微任务呢,这应该是Vue保证的,在Vue生命周期或者事件函数里添加微任务,微任务会在Dom更新后,浏览器重新渲染页面前执行。所以猜测Vue每次会在执行用户代码之前先添加更新Dom的微任务。等我看看源码再来和大家分享。

 

问题3

哪些函数能添加微任务,哪些函数能添加宏任务呢?

宏任务: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O
微任务: process.nextTick, Promises, Object.observe, MutationObserver

其中requestAnimationFrame,比较特殊

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。这个函数实际测试,会在微任务之后,浏览器重新渲染界面之前执行。很多动画库都是利用了这个函数。

 

参考文章:

https://github.com/aooy/blog/issues/5

https://segmentfault.com/q/1010000017571945

https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值