$nextTick的源码核心逻辑分析

本文详细解析了Vue.js中nextTick的实现,它用于异步更新队列,并在适当的时机执行回调函数。核心逻辑包括收集回调、根据浏览器环境选择延迟执行策略(Promise、MutationObserver、setImmediate、setTimeout)。Vue优先使用微任务,确保在DOM更新后执行。文章还介绍了flushCallbacks函数,用于执行回调并重置状态。整个流程确保了在适当的时间执行回调,以保持正确的执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码用了flow做静态检查,这里去除flow部分

核心逻辑其实就两步:

  • 保存回调函数
  • 根据不同浏览器的情况选择不同的方法延迟执行回调函数

首先看函数nextTick的实现:

const callbacks = []
let pending = false
let timerFunc

// cb: 回调函数
// ctx: 用于改变this指向
function nextTick (cb, ctx) {
  let _resolve // 保存通过then传入的回调函数
  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,通过_resolve保存then传入的回调函数,将_resolve的调用保存在数组中。
接着,通过pending保证在同一作用域下nextTick只调用一次。在这里调用timerFunc延迟执行callbacks里面的回调函数。
现在我们来看看timerFunc的代码:

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

// noop: 一个空函数
// isIE:是否是IE环境
// isIOS: 是否IOS环境
// isNative: 是否是浏览器等原生支持

let timerFunc
let isUsingMicroTask = false // 是否使用了微任务

// 在不同环境下选择不同方法延迟,首先选择微任务,
// 微任务不可以再利用宏任务
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
    // 如果是IOS环境,由于Promise.then可能会出现一些情况:
    // 例如回调被推入微任务队列中,但是没有被执行,这时可
    // 以通过做一些额外的操作强行刷新微任务队列。这里使用
    // 一个空的计时器刷新微任务队列。
    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)
  }
}

从上述代码看出,Vue做延迟操作使用的API优先级是:Promise > MutationObserver > setImmediate > setTimeout。其中前两个是微任务,后两个是宏任务。在延迟结束后,调用flushCallbacks执行回调函数。flushCallbacks代码如下:

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

从中看出,这个函数就是循环调用了回调函数然后初始化callbackspending而已。
最后梳理一下代码执行逻辑:

  1. 判断执行环境,选择合适的API做延迟处理,选择标准是微任务优先于宏任务。将操作封装在timerFunc函数中。
  2. 收集回调函数,判断是否显式的传入了回调函数,如果是则直接保存这个回调函数的调用到callbacks,如果不是则返回一个Promise,通过_resolve保存then传入的回调函数。
  3. 执行timerFunc函数,通过pending保证同一作用域多次调用nextTick时只触发一次。延迟结束后执行callbacks中的回调函数并初始化callbackspending

完整源码如下:

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

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值