「Vue」nextTick 做了什么?

  |   0 评论   |   0 浏览   |   Erioifpud

代码

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

用法如下:

this.$nextTick(() => {})
this.$nextTick().then(() => {})

首先看关键的 timerFunc,代码中的绝大部分都是为 timerFunc 赋值设计的,他有 4 种场景,分别是:

if (typeof Promise !== 'undefined' && isNative(Promise)) {
	// 1
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
	isNative(MutationObserver) ||
	MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
	// 2
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // 3
} else {
  // 4
}

Promise.then

首先先检查浏览器支不支持 Promise,并且 Promise 是否是原生的,因为原生的 Promise.then 属于微任务,能在宏任务完成后立即执行,算是最高优先级

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
// ...
export function noop (a?: any, b?: any, c?: any) {}

这里的 timerFunc 就会成为一个“以微任务形式调用 flushCallbacks 的函数”,这里还额外判断了是否为 iOS 环境,原因在注释里:

在一些有问题的 UIWebViews 中,任务进了微任务队列,但是没有被正确地执行(清空),这里需要一个宏任务去强制让微任务清空。

再将“使用微任务”的标记 isUsingMicroTask 设置为 true

MutationObserver

其次检查浏览器是否为 IE(11 前均不支持),并且对于 MutationObserver 进行“是否支持”、“是否原生”、“是否被纂改”的检查,目的就是为了使用 MutationObserver

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

MutationObserver 是用来检查 DOM 节点变化的,他也属于微任务。

这里会创建一个文本节点,并且观察它,timerFunc让文本节点的内容发生变化,触发更新。(这里为什么不清除)

setImmediate

如果前两个 API 都不支持,那么就会回退到 setImmediate

timerFunc = () => {
  setImmediate(flushCallbacks)
}

这里已经是宏任务了,优先级比微任务低一点。

setTimeout

最后是使用 setTimeout 进行宏任务的兜底:

timerFunc = () => {
  setTimeout(flushCallbacks)
}

nextTick 本体

接着看最下方的函数实现,nextTick 会收集所有来自参数的 cbcallbacks 中,统一执行

如果没有提供 cb,他会返回一个 Promise,并且提取出 resolve 函数放进 callbacks,就是为了让 callbacks 执行后能够使 Promise 进入 fulfilled

之后会判断 pending,这是一个“执行中”的标志,在调用 nextTick 后把任务放进到 callbacks 前都属于执行中,直到 callbacks 真正开始被处理,这时 pending 才会被反转。

这样做的意义是,如果频繁调用 nextTick

可以理解成,把宏任务/微任务(具体看 timerFunc 选择哪种方案)的执行看作是一个周期性的动作,那么在一个周期内调用 nextTick 添加的任务都会在下一个周期统一执行pending 就相当于时周期内的一个 🔒。

flushCallbacks

之前看到 timerFunc 是以“不断回退”的方式去将 flushCallbacks 设置成异步任务,那 flushCallbacks 到底是什么呢?

跳回开头,flushCallbacks 首先会将 pending 解锁,这时是在宏任务/微任务新周期的开头,随后他会创建一个 callbacks 的浅拷贝,并且将原来的 callbacks 清空,这里是为了让出数组空间给下一个周期的任务使用。

最后就是遍历并且执行 callbacks 中所有的任务。

总结

nextTick 的步骤可以总结成以下几点:

  1. 以回退的方式去设置 timerFunc
  2. 将参数的 cb 或自己创建出 Promise.resolve 作为任务放进 callbacks
  3. 使用 pending 锁定执行,确保每个周期只执行一次 timeFunc → flushCallbacks
  4. flushCallbacks 遍历所有任务并且执行。

isUsingMicroTask 这个标志在 nextTick 里没有直接使用到。


标题:「Vue」nextTick 做了什么?
作者:Erioifpud
地址:https://blog.doiduoyi.com/articles/1628002787986.html

评论

发表评论