资讯专栏INFORMATION COLUMN

Vue源码中的nextTick的实现逻辑

Anshiii / 1638人阅读

摘要:这是因为在运行时出错,我们不这个错误的话,会导致整个程序崩溃掉。如果没有向中传入,并且浏览器支持的话,我们的返回的将是一个。如果不支持,就降低到用,整体逻辑就是这样。。

我们知道vue中有一个api。Vue.nextTick( [callback, context] )
他的作用是在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。那么这个api是怎么实现的呢?你肯定也有些疑问或者好奇。下面就是我的探索,分享给大家,也欢迎大家到github上和我进行讨论哈~~

首先贴一下vue的源码,然后我们再一步步的分析

</>复制代码

  1. /* @flow */
  2. /* globals MessageChannel */
  3. import { noop } from "shared/util"
  4. import { handleError } from "./error"
  5. import { isIOS, isNative } from "./env"
  6. const callbacks = []
  7. let pending = false
  8. function flushCallbacks () {
  9. pending = false
  10. const copies = callbacks.slice(0)
  11. callbacks.length = 0
  12. for (let i = 0; i < copies.length; i++) {
  13. copies[i]()
  14. }
  15. }
  16. // Here we have async deferring wrappers using both microtasks and (macro) tasks.
  17. // In < 2.4 we used microtasks everywhere, but there are some scenarios where
  18. // microtasks have too high a priority and fire in between supposedly
  19. // sequential events (e.g. #4521, #6690) or even between bubbling of the same
  20. // event (#6566). However, using (macro) tasks everywhere also has subtle problems
  21. // when state is changed right before repaint (e.g. #6813, out-in transitions).
  22. // Here we use microtask by default, but expose a way to force (macro) task when
  23. // needed (e.g. in event handlers attached by v-on).
  24. let microTimerFunc
  25. let macroTimerFunc
  26. let useMacroTask = false
  27. // Determine (macro) task defer implementation.
  28. // Technically setImmediate should be the ideal choice, but it"s only available
  29. // in IE. The only polyfill that consistently queues the callback after all DOM
  30. // events triggered in the same loop is by using MessageChannel.
  31. /* istanbul ignore if */
  32. if (typeof setImmediate !== "undefined" && isNative(setImmediate)) {
  33. macroTimerFunc = () => {
  34. setImmediate(flushCallbacks)
  35. }
  36. } else if (typeof MessageChannel !== "undefined" && (
  37. isNative(MessageChannel) ||
  38. // PhantomJS
  39. MessageChannel.toString() === "[object MessageChannelConstructor]"
  40. )) {
  41. const channel = new MessageChannel()
  42. const port = channel.port2
  43. channel.port1.onmessage = flushCallbacks
  44. macroTimerFunc = () => {
  45. port.postMessage(1)
  46. }
  47. } else {
  48. /* istanbul ignore next */
  49. macroTimerFunc = () => {
  50. setTimeout(flushCallbacks, 0)
  51. }
  52. }
  53. // Determine microtask defer implementation.
  54. /* istanbul ignore next, $flow-disable-line */
  55. if (typeof Promise !== "undefined" && isNative(Promise)) {
  56. const p = Promise.resolve()
  57. microTimerFunc = () => {
  58. p.then(flushCallbacks)
  59. // in problematic UIWebViews, Promise.then doesn"t completely break, but
  60. // it can get stuck in a weird state where callbacks are pushed into the
  61. // microtask queue but the queue isn"t being flushed, until the browser
  62. // needs to do some other work, e.g. handle a timer. Therefore we can
  63. // "force" the microtask queue to be flushed by adding an empty timer.
  64. if (isIOS) setTimeout(noop)
  65. }
  66. } else {
  67. // fallback to macro
  68. microTimerFunc = macroTimerFunc
  69. }
  70. /**
  71. * Wrap a function so that if any code inside triggers state change,
  72. * the changes are queued using a (macro) task instead of a microtask.
  73. */
  74. export function withMacroTask (fn: Function): Function {
  75. return fn._withTask || (fn._withTask = function () {
  76. useMacroTask = true
  77. const res = fn.apply(null, arguments)
  78. useMacroTask = false
  79. return res
  80. })
  81. }
  82. export function nextTick (cb?: Function, ctx?: Object) {
  83. let _resolve
  84. callbacks.push(() => {
  85. if (cb) {
  86. try {
  87. cb.call(ctx)
  88. } catch (e) {
  89. handleError(e, ctx, "nextTick")
  90. }
  91. } else if (_resolve) {
  92. _resolve(ctx)
  93. }
  94. })
  95. if (!pending) {
  96. pending = true
  97. if (useMacroTask) {
  98. macroTimerFunc()
  99. } else {
  100. microTimerFunc()
  101. }
  102. }
  103. // $flow-disable-line
  104. if (!cb && typeof Promise !== "undefined") {
  105. return new Promise(resolve => {
  106. _resolve = resolve
  107. })
  108. }
  109. }

这么多代码,可能猛的一看,可能有点懵,不要紧,我们一步一步抽出枝干。首先我们看一下这个js文件里的nextTick的定义

</>复制代码

  1. export function nextTick (cb?: Function, ctx?: Object) {
  2. let _resolve
  3. callbacks.push(() => {
  4. if (cb) {
  5. try {
  6. cb.call(ctx)
  7. } catch (e) {
  8. handleError(e, ctx, "nextTick")
  9. }
  10. } else if (_resolve) {
  11. _resolve(ctx)
  12. }
  13. })
  14. if (!pending) {
  15. pending = true
  16. if (useMacroTask) {
  17. macroTimerFunc()
  18. } else {
  19. microTimerFunc()
  20. }
  21. }
  22. // $flow-disable-line
  23. if (!cb && typeof Promise !== "undefined") {
  24. return new Promise(resolve => {
  25. _resolve = resolve
  26. })
  27. }
  28. }

我将代码精简一下。如下所示,下面的代码估计就比较容易看懂了。把cb函数放到会掉队列里去,如果支持macroTask,则利用macroTask在下一个事件循环中执行这些异步的任务,如果不支持macroTask,那就利用microTask在下一个事件循环中执行这些异步任务。

</>复制代码

  1. export function nextTick (cb?: Function, ctx?: Object) {
  2. callbacks.push(cb)
  3. if (useMacroTask) {
  4. macroTimerFunc()
  5. } else {
  6. microTimerFunc()
  7. }
  8. }

这里再次普及一下js的event loop的相关知识,js中的两个任务队列 :macrotasks、microtasks

macrotasks: script(一个js文件),setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks: process.nextTick, Promises, Object.observe, MutationObserver

执行过程:
1.js引擎从macrotask队列中取一个任务执行
2.然后将microtask队列中的所有任务依次执行完
3.再次从macrotask队列中取一个任务执行
4.然后再次将microtask队列中所有任务依次执行完
……
循环往复

那么我们再看我们精简掉的代码都是干什么的呢?我们往异步队列里放回调函数的时候,我们并不是直接放回调函数,而是包装了一个函数,在这个函数里调用cb,并且用try catch包裹了一下。这是因为cb在运行时出错,我们不try catch这个错误的话,会导致整个程序崩溃掉。 我们还精简掉了如下代码

</>复制代码

  1. if (!cb && typeof Promise !== "undefined") {
  2. return new Promise(resolve => {
  3. _resolve = resolve
  4. })
  5. }

这段代码是干嘛的呢?也就是说我们用nextTick的时候,还可以有promise的写法。如果没有向nextTick中传入cb,并且浏览器支持Promise的话,我们的nextTick返回的将是一个Promise。所以,nextTick的写法也可以是如下这样的

</>复制代码

  1. nextTick().then(()=>{console.log("XXXXX")})

vue源码里关于nextTick的封装的思路,也给我们一些非常有益的启示,就是我们平时在封装函数的时候,要想同时指出回调和promise的话,就可以借鉴vue中的思路。

大致的思路我们已经捋顺了。但是为什么执行macroTimerFunc或者microTimerFunc就会在下一个tick执行我们的回调队列呢?下面我们来分析一下这两个函数的定义。首先我们分析macroTimerFunc

</>复制代码

  1. let macroTimerFunc
  2. if (typeof setImmediate !== "undefined" && isNative(setImmediate)) {
  3. macroTimerFunc = () => {
  4. setImmediate(flushCallbacks)
  5. }
  6. } else if (typeof MessageChannel !== "undefined" && (
  7. isNative(MessageChannel) ||
  8. // PhantomJS
  9. MessageChannel.toString() === "[object MessageChannelConstructor]"
  10. )) {
  11. const channel = new MessageChannel()
  12. const port = channel.port2
  13. channel.port1.onmessage = flushCallbacks
  14. macroTimerFunc = () => {
  15. port.postMessage(1)
  16. }
  17. } else {
  18. /* istanbul ignore next */
  19. macroTimerFunc = () => {
  20. setTimeout(flushCallbacks, 0)
  21. }
  22. }

从上边的代码可以看出,如果浏览器支持setImmediate,我们就用setImmediate,如果浏览器支持MessageChannel,我们就用MessageChannel的异步特性,如果两者都不支持,我们就降价到setTimeout
,用setTimeout来把callbacks中的任务在下一个tick中执行

</>复制代码

  1. macroTimerFunc = () => {
  2. setTimeout(flushCallbacks, 0)
  3. }

分析完macroTimerFunc,下面我们开始分析microTimerFunc,我把vue源码中关于microTimerFunc的定义稍微精简一下

</>复制代码

  1. let microTimerFunc;
  2. if (typeof Promise !== "undefined" && isNative(Promise)) {
  3. const p = Promise.resolve()
  4. microTimerFunc = () => {
  5. p.then(flushCallbacks)
  6. }
  7. } else {
  8. // fallback to macro
  9. microTimerFunc = macroTimerFunc
  10. }

从上边精简之后的代码,我们可以看到microTimerFunc的实现思路。如果支持浏览器支持promise,就用promise实现。如果不支持,就降低到用macroTimerFunc

over,整体逻辑就是这样。。看着吓人,掰开了之后好好分析一下,还是挺简单的。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/96240.html

相关文章

  • 详细分析Vue.nextTick()实现

    摘要:因为平时使用都是传回调的,所以很好奇什么情况下会为,去翻看官方文档发现起新增如果没有提供回调且在支持的环境中,则返回一个。这就对了,函数体内最后的判断很明显就是这个意思没有回调支持。 Firstly, this paper is based on Vue 2.6.8刚开始接触Vue的时候,哇nextTick好强,咋就在这里面写就是dom更新之后,当时连什么macrotask、micro...

    DevYK 评论0 收藏0
  • 你不知道$nextTick

    摘要:复制代码然后在这个文件里还有一个函数叫用来把保存的回调函数给全执行并清空。其实调用的不仅是开发者,更新时,也用到了。但是问题又来了,根据浏览器的渲染机制,渲染线程是在微任务执行完成之后运行的。 当在代码中更新了数据,并希望等到对应的Dom更新之后,再执行一些逻辑。这时,我们就会用到$nextTickfuncion call...

    番茄西红柿 评论0 收藏2637
  • Vue源码详解之nextTick:MutationObserver只是浮云,microtask才是核

    摘要:后来尤雨溪了解到是将回调放入的队列。而且浏览器内部为了更快的响应用户,内部可能是有多个的而的的优先级可能更高,因此对于尤雨溪采用的,甚至可能已经多次执行了的,都没有执行的,也就导致了我们更新操 原发于我的博客。 前一篇文章已经详细记述了Vue的核心执行过程。相当于已经搞定了主线剧情。后续的文章都会对其中没有介绍的细节进行展开。 现在我们就来讲讲其他支线任务:nextTick和micro...

    陈伟 评论0 收藏0
  • VueJS源码学习——元素在插入和移出 dom 时过渡逻辑

    摘要:原文地址项目地址关于中使用效果,官网上的解释如下当元素插入到树或者从树中移除的时候,属性提供变换的效果,可以使用来定义变化效果,也可以使用来定义首先第一个函数是将元素插入,函数实现调用了实现代码如下写的好的代码就是文档,从注释和命名上就 src/transition 原文地址项目地址 关于 vue 中使用 transition 效果,官网上的解释如下: With Vue.js’ tra...

    Dogee 评论0 收藏0
  • Vue原理】NextTick - 源码版 之 独立自身

    摘要:尽量把所有异步代码放在一个宏微任务中,减少消耗加快异步代码的执行。我们知道,如果一个异步代码就注册一个宏微任务的话,那么执行完全部异步代码肯定慢很多避免频繁地更新。中就算我们一次性修改多次数据,页面还是只会更新一次。 写文章不容易,点个赞呗兄弟专注 Vue 源码分享,文章分为白话版和 源码版,白话版助于理解工作原理,源码版助于了解内部详情,让我们一起学习吧研究基于 Vue版本 【2.5...

    刘东 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<