图解 Vue 异步更新原理

开发 前端
本文主要分析 Vue 从 Data 更新,到通知 Watcher 异步更新视图的流程,也就是下图中的橙色部分。

[[340964]]

本文转载自微信公众号「 前端日志」,作者 前端日志。转载本文请联系 前端日志公众号。

 本文主要分析 Vue 从 Data 更新,到通知 Watcher 异步更新视图的流程,也就是下图中的橙色部分。

 

我们先来回顾一下图中的几个对象:

  • Data 对象:Vue 中的 data 方法中返回的对象。
  • Dep 对象:每一个 Data 属性都会创建一个 Dep,用来搜集所有使用到这个 Data 的 Watcher 对象。
  • Watcher 对象:主要用于渲染 DOM。

接下来,我们就开始分析这个流程。

Vue 异步更新 DOM 原理

很多同学都知道,Vue 中的数据更新是异步的,意味着我们在修改完 Data 之后,并不能立刻获取修改后的 DOM 元素。

例如:

  1. <template> 
  2.   <div> 
  3.     <span id="text">{{ message }}</span> 
  4.     <button @click="changeData"
  5.       changeData 
  6.     </button> 
  7.   </div> 
  8. </template> 
  9.  
  10. <script> 
  11. export default { 
  12.   data() { 
  13.     return { 
  14.       message: "hello"
  15.     }; 
  16.   }, 
  17.   methods: { 
  18.     changeData() { 
  19.       this.message = "hello world"
  20.       const textContent = document.getElementById("text").textContent; 
  21.       // 直接获取,不是最新的 
  22.       console.log(textContent === "hello world"); // false 
  23.             // $nextTick 回调中,是最新的 
  24.       this.$nextTick(() => { 
  25.         const textContent = document.getElementById("text").textContent; 
  26.         console.warn(textContent === "hello world"); // true 
  27.       }); 
  28.     }, 
  29.   }, 
  30. }; 
  31. </script> 

 

什么时候我们才能获取到真正的 DOM 元素?

答:在 Vue 的 nextTick 回调中。

这一点在 Vue 官网有详细的介绍,但你是否有想过,为什么 Vue 需要通过 nextTick 方法才能获取最新的 DOM?

带着这个疑问,我们直接看一下源码。

  1. // 当一个 Data 更新时,会依次执行以下代码 
  2. // 1. 触发 Data.set 
  3. // 2. 调用 dep.notify 
  4. // 3. Dep 会遍历所有相关的 Watcher 执行 update 方法 
  5. class Watcher { 
  6.   // 4. 执行更新操作 
  7.   update() { 
  8.     queueWatcher(this); 
  9.   } 
  10.  
  11. const queue = []; 
  12.  
  13. function queueWatcher(watcher: Watcher) { 
  14.   // 5. 将当前 Watcher 添加到异步队列 
  15.   queue.push(watcher); 
  16.   // 6. 执行异步队列,并传入回调 
  17.   nextTick(flushSchedulerQueue); 
  18.  
  19. // 更新视图的具体方法 
  20. function flushSchedulerQueue() { 
  21.   let watcher, id; 
  22.   // 排序,先渲染父节点,再渲染子节点 
  23.   // 这样可以避免不必要的子节点渲染,如:父节点中 v-if 为 false 的子节点,就不用渲染了 
  24.   queue.sort((a, b) => a.id - b.id); 
  25.   // 遍历所有 Watcher 进行批量更新。 
  26.   for (index = 0; index < queue.length; index++) { 
  27.     watcher = queue[index]; 
  28.     // 更新 DOM 
  29.     watcher.run(); 
  30.   } 

根据上面的代码,我们可以得出这样一个流程图:

 

图中可以看到,Vue 在调用 Watcher 更新视图时,并不会直接进行更新,而是把需要更新的 Watcher 加入到 Queue 队列里,然后把具体的更新方法 flushSchedulerQueue 传给 nextTick 进行调用。

接下来,我们分析一下 nextTick。

  1. const callbacks = []; 
  2. let timerFunc; 
  3.  
  4. function nextTick(cb?: Function, ctx?: Object) { 
  5.   let _resolve; 
  6.   // 1.将传入的 flushSchedulerQueue 方法添加到回调数组 
  7.   callbacks.push(() => { 
  8.     cb.call(ctx); 
  9.   }); 
  10.   // 2.执行异步任务 
  11.   // 此方法会根据浏览器兼容性,选用不同的异步策略 
  12.   timerFunc(); 

可以看到,nextTick 函数非常简单,它只是将传入的 flushSchedulerQueue 添加到 callbacks 数组中,然后执行了 timerFunc 方法。

接下来,我们分析一下 timerFunc 方法。

  1. let timerFunc; 
  2. // 判断是否兼容 Promise 
  3. if (typeof Promise !== "undefined") { 
  4.   timerFunc = () => { 
  5.     Promise.resolve().then(flushCallbacks); 
  6.   }; 
  7.   // 判断是否兼容 MutationObserver 
  8.   // https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver 
  9. else if (typeof MutationObserver !== "undefined") { 
  10.   let counter = 1; 
  11.   const observer = new MutationObserver(flushCallbacks); 
  12.   const textNode = document.createTextNode(String(counter)); 
  13.   observer.observe(textNode, { 
  14.     characterData: true
  15.   }); 
  16.   timerFunc = () => { 
  17.     counter = (counter + 1) % 2; 
  18.     textNode.data = String(counter); 
  19.   }; 
  20.   // 判断是否兼容 setImmediate 
  21.   // 该方法存在一些 IE 浏览器中 
  22. else if (typeof setImmediate !== "undefined") { 
  23.   // 这是一个宏任务,但相比 setTimeout 要更好 
  24.   timerFunc = () => { 
  25.     setImmediate(flushCallbacks); 
  26.   }; 
  27. else { 
  28.   // 如果以上方法都不知道,使用 setTimeout 0 
  29.   timerFunc = () => { 
  30.     setTimeout(flushCallbacks, 0); 
  31.   }; 
  32.  
  33. // 异步执行完后,执行所有的回调方法,也就是执行 flushSchedulerQueue 
  34. function flushCallbacks() { 
  35.   for (let i = 0; i < copies.length; i++) { 
  36.     callbacks[i](); 
  37.   } 

可以看到,timerFunc 是根据浏览器兼容性创建的一个异步方法,它执行完成之后,会调用 flushSchedulerQueue 方法进行具体的 DOM 更新。

分析到这里,我们就可以得到一张整体的流程图了。

 

接下来,我们来完善一些判断逻辑。

  • 判断 has 标识,避免在一个 Queue 中添加相同的 Watcher。
  • 判断 waiting 标识,让所有的 Watcher 都在一个 tick 内进行更新。
  • 判断 flushing 标识,处理 Watcher 渲染时,可能产生的新 Watcher。

如:触发了 v-if 的条件,新增的 Watcher 渲染。

结合以上判断,最终的流程图如下:

 

最后,我们分析一下,为什么 this.$nextTick 能够获取更新后的 DOM?

  1. // 我们使用 this.$nextTick 其实就是调用 nextTick 方法 
  2. Vue.prototype.$nextTick = function (fn: Function) { 
  3.   return nextTick(fn, this); 
  4. }; 

可以看到,调用 this.$nextTick 其实就是调用了图中的 nextTick 方法,在异步队列中执行回调函数。根据先来后到原则,修改 Data 触发的更新异步队列会先得到执行,执行完成后就生成了新的 DOM ,接下来执行 this.$nextTick 的回调函数时,能获取到更新后的 DOM 元素了。

由于 nextTick 只是单纯通过 Promise 、SetTimeout 等方法模拟的异步任务,所以也可以手动执行一个异步任务,来实现和 this.$nextTick 相同的效果。

  1. this.message = "hello world"
  2. // 手动执行一个异步任务,也能获取最新的 DOM 
  3. Promise.resolve().then(() => { 
  4.   const textContent = document.getElementById("text").textContent; 
  5.   console.log(textContent === "hello world"); // true 
  6. }); 
  7. setTimeout(() => { 
  8.   const textContent = document.getElementById("text").textContent; 
  9.   console.log(textContent === "hello world"); // true 
  10. }); 

思考与总结

本文从源码的角度,介绍了 Vue 异步更新的原理,来简单回顾一下吧。

修改 Vue 中的 Data 时,就会触发所有和这个 Data 相关的 Watcher 进行更新。

首先,会将所有的 Watcher 加入队列 Queue。

然后,调用 nextTick 方法,执行异步任务。

在异步任务的回调中,对 Queue 中的 Watcher 进行排序,然后执行对应的 DOM 更新。

责任编辑:武晓燕 来源: 前端日志
相关推荐

2020-09-21 14:35:20

VuenextTick前端

2021-02-05 15:01:41

GitLinux命令

2021-06-09 10:29:23

Kafka架构组件

2021-04-09 08:54:14

Kafka源码架构开发技术

2024-03-08 10:38:07

Vue响应式数据

2021-08-02 07:57:03

注册Nacos源码

2021-12-07 07:32:09

kafka架构原理

2022-11-08 00:00:00

监控系统Prometheus

2021-09-29 11:33:19

异步组件Vue 3

2020-09-14 08:56:30

Vue模板

2021-05-19 09:29:52

VueAxios异步请求

2020-11-30 07:54:46

ElasticSear开源分布式

2017-12-26 17:42:12

前端WebGLThree.js

2020-12-09 10:29:53

SSH加密数据安全

2010-02-04 10:17:38

Android应用程序

2023-09-19 08:12:18

2023-01-04 13:43:24

读写锁AQS共享模式

2021-02-09 09:51:58

异步传递数据

2023-03-13 17:18:09

OkHttp同步异步

2022-08-30 09:01:11

浏览器渲染前端
点赞
收藏

51CTO技术栈公众号