nextTick 在 vue 2.5 和 vue 2.6 之间有什么不同

栏目: 编程语言 · 发布时间: 5年前

内容简介:我们知道对于 Vue 来说,从数据变化到执行 DOM 更新,这个过程是它会创建一个更新队列在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

我们知道对于 Vue 来说,从数据变化到执行 DOM 更新,这个过程是 异步 的,发生在下一个 tick 里。

它会创建一个更新队列 queue ,队列中维护着各个属性的 watcher ,在需要时执行、更新它们。

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

Vue.nextTick()
    .then(function () {
    	// DOM 更新了
	})
复制代码

那么针对这样一个核心功能,Vue 2.5 与 Vue 2.6 的实现有什么不同呢?

可能需要你简单了解下 js 的 event loop。 模拟实现 JS 引擎:深入了解 JS机制 以及 Microtask and Macrotask

Vue 2.5 nextTick 实现

在 Vue 2.5 中,nextTick 的实现是 microTimerFuncmacroTimerFunc 组合实现的,具体见源码。

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

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 both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    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)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

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
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
复制代码

比较关键的几行

let useMacroTask = false

if (!pending) {
    pending = true
    if (useMacroTask) {
    	macroTimerFunc()
    } else {
    	microTimerFunc()
    }
}
复制代码

这里说明,Vue 2.5 会优先使用 microTimerFunc ,如果存在兼容性问题,则降级为 macroTimerFunc

microTimerFunc 的实现:原生的 Promise

macroTimerFunc 的实现: setImmediate || MessageChannel || setTimeout

同时 Vue 2.5 的 next-tick 还对外暴露了两个函数: nextTick 以及 withMacroTask (用于处理一些 DOM 交互事件,如 v-on 绑定的事件回调函数的处理,会强制走 macro task)。

通读源码,发现逻辑很清晰,也完成优雅渐进,那么发什么了导致 Vue 在 2.6 对其进行了 fix 呢?来看一段 Vue 2.6 的注释

// 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).
复制代码

主要阐明了两个问题:

  • 在重绘之前状态发生改变会有轻微的问题;
  • 利用 macro task 处理事件时,会产生一系列无法规避的诡异问题。

简单地描述下这两个问题:

第一个问题,具体见图

nextTick 在 vue 2.5 和 vue 2.6 之间有什么不同

试一试,具体描述见 github.com/vuejs/vue/i… ,本质上就是在 css 中定义了 @media 媒体查询,js 中 window 监听了 resize 事件,那么当触发固定阈值时,state 发生了变化、样式也需要重绘,这就产生了问题。

第二个问题,一般可以概括为由于使用 macroTask 处理 DOM 操作,会使得有些时候触发和执行之间间隔太大,例如在移动端,单击的 handler 和音频播放功能不在同一 tick 里。

Vue2.6 nextTick 实现

由于以上问题,所以在 Vue 2.6 实现过程中,利用 microtasks 代替之前的解决方案,具体见源码。

/* @flow */
/* globals MutationObserver */

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

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)
  }
} 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)
  }
} 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
    })
  }
}
复制代码

Vue 2.6 利用最典型的两个 microTask, promise.then 以及 Mutation observers ,并添加 setImmediatesetImmediate ,作为降级方案。

只对外暴露了一个接口 next-tick,同时用 microTask 来处理 event handler。这种实现方法解决了上述问题,但是也有一个很明显的弊端。由于 microTask 的优先级太高,导致当连续触发 event 事件时产生问题,具体见注释。


以上所述就是小编给大家介绍的《nextTick 在 vue 2.5 和 vue 2.6 之间有什么不同》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

打破界限

打破界限

电通跨媒体开发项目组 / 苏友友 / 中信出版社 / 2011-10 / 35.00元

《打破界限:电通式跨媒体沟通策略》是日本电通跨媒体沟通开发项目组对“跨媒体”的思考方式、策划工具、成功案例和评估手段等诸多内容进行深入研究得到的丰硕成果,深刻剖析了此营销模式的本质。 目前,为客户提供整合式营销解决方案的电通模式在世界各国都获得了很高评价。而跨媒体沟通正是电通实现这种模式最先进的工具之一。一起来看看 《打破界限》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具