自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

圖解 Vue 異步更新原理

開發(fā) 前端
本文主要分析 Vue 從 Data 更新,到通知 Watcher 異步更新視圖的流程,也就是下圖中的橙色部分。

[[340964]]

本文轉(zhuǎn)載自微信公眾號(hào)「 前端日志」,作者 前端日志。轉(zhuǎn)載本文請(qǐng)聯(lián)系 前端日志公眾號(hào)。

 本文主要分析 Vue 從 Data 更新,到通知 Watcher 異步更新視圖的流程,也就是下圖中的橙色部分。

 

我們先來回顧一下圖中的幾個(gè)對(duì)象:

  • Data 對(duì)象:Vue 中的 data 方法中返回的對(duì)象。
  • Dep 對(duì)象:每一個(gè) Data 屬性都會(huì)創(chuàng)建一個(gè) Dep,用來搜集所有使用到這個(gè) Data 的 Watcher 對(duì)象。
  • Watcher 對(duì)象:主要用于渲染 DOM。

接下來,我們就開始分析這個(gè)流程。

Vue 異步更新 DOM 原理

很多同學(xué)都知道,Vue 中的數(shù)據(jù)更新是異步的,意味著我們?cè)谛薷耐?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 回調(diào)中,是最新的 
  24.       this.$nextTick(() => { 
  25.         const textContent = document.getElementById("text").textContent; 
  26.         console.warn(textContent === "hello world"); // true 
  27.       }); 
  28.     }, 
  29.   }, 
  30. }; 
  31. </script> 

 

什么時(shí)候我們才能獲取到真正的 DOM 元素?

答:在 Vue 的 nextTick 回調(diào)中。

這一點(diǎn)在 Vue 官網(wǎng)有詳細(xì)的介紹,但你是否有想過,為什么 Vue 需要通過 nextTick 方法才能獲取最新的 DOM?

帶著這個(gè)疑問,我們直接看一下源碼。

  1. // 當(dāng)一個(gè) Data 更新時(shí),會(huì)依次執(zhí)行以下代碼 
  2. // 1. 觸發(fā) Data.set 
  3. // 2. 調(diào)用 dep.notify 
  4. // 3. Dep 會(huì)遍歷所有相關(guān)的 Watcher 執(zhí)行 update 方法 
  5. class Watcher { 
  6.   // 4. 執(zhí)行更新操作 
  7.   update() { 
  8.     queueWatcher(this); 
  9.   } 
  10.  
  11. const queue = []; 
  12.  
  13. function queueWatcher(watcher: Watcher) { 
  14.   // 5. 將當(dāng)前 Watcher 添加到異步隊(duì)列 
  15.   queue.push(watcher); 
  16.   // 6. 執(zhí)行異步隊(duì)列,并傳入回調(diào) 
  17.   nextTick(flushSchedulerQueue); 
  18.  
  19. // 更新視圖的具體方法 
  20. function flushSchedulerQueue() { 
  21.   let watcher, id; 
  22.   // 排序,先渲染父節(jié)點(diǎn),再渲染子節(jié)點(diǎn) 
  23.   // 這樣可以避免不必要的子節(jié)點(diǎn)渲染,如:父節(jié)點(diǎn)中 v-if 為 false 的子節(jié)點(diǎn),就不用渲染了 
  24.   queue.sort((a, b) => a.id - b.id); 
  25.   // 遍歷所有 Watcher 進(jìn)行批量更新。 
  26.   for (index = 0; index < queue.length; index++) { 
  27.     watcher = queue[index]; 
  28.     // 更新 DOM 
  29.     watcher.run(); 
  30.   } 

根據(jù)上面的代碼,我們可以得出這樣一個(gè)流程圖:

 

圖中可以看到,Vue 在調(diào)用 Watcher 更新視圖時(shí),并不會(huì)直接進(jìn)行更新,而是把需要更新的 Watcher 加入到 Queue 隊(duì)列里,然后把具體的更新方法 flushSchedulerQueue 傳給 nextTick 進(jìn)行調(diào)用。

接下來,我們分析一下 nextTick。

  1. const callbacks = []; 
  2. let timerFunc; 
  3.  
  4. function nextTick(cb?: Function, ctx?: Object) { 
  5.   let _resolve; 
  6.   // 1.將傳入的 flushSchedulerQueue 方法添加到回調(diào)數(shù)組 
  7.   callbacks.push(() => { 
  8.     cb.call(ctx); 
  9.   }); 
  10.   // 2.執(zhí)行異步任務(wù) 
  11.   // 此方法會(huì)根據(jù)瀏覽器兼容性,選用不同的異步策略 
  12.   timerFunc(); 

可以看到,nextTick 函數(shù)非常簡(jiǎn)單,它只是將傳入的 flushSchedulerQueue 添加到 callbacks 數(shù)組中,然后執(zhí)行了 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.   // 這是一個(gè)宏任務(wù),但相比 setTimeout 要更好 
  24.   timerFunc = () => { 
  25.     setImmediate(flushCallbacks); 
  26.   }; 
  27. else { 
  28.   // 如果以上方法都不知道,使用 setTimeout 0 
  29.   timerFunc = () => { 
  30.     setTimeout(flushCallbacks, 0); 
  31.   }; 
  32.  
  33. // 異步執(zhí)行完后,執(zhí)行所有的回調(diào)方法,也就是執(zhí)行 flushSchedulerQueue 
  34. function flushCallbacks() { 
  35.   for (let i = 0; i < copies.length; i++) { 
  36.     callbacks[i](); 
  37.   } 

可以看到,timerFunc 是根據(jù)瀏覽器兼容性創(chuàng)建的一個(gè)異步方法,它執(zhí)行完成之后,會(huì)調(diào)用 flushSchedulerQueue 方法進(jìn)行具體的 DOM 更新。

分析到這里,我們就可以得到一張整體的流程圖了。

 

接下來,我們來完善一些判斷邏輯。

  • 判斷 has 標(biāo)識(shí),避免在一個(gè) Queue 中添加相同的 Watcher。
  • 判斷 waiting 標(biāo)識(shí),讓所有的 Watcher 都在一個(gè) tick 內(nèi)進(jìn)行更新。
  • 判斷 flushing 標(biāo)識(shí),處理 Watcher 渲染時(shí),可能產(chǎn)生的新 Watcher。

如:觸發(fā)了 v-if 的條件,新增的 Watcher 渲染。

結(jié)合以上判斷,最終的流程圖如下:

 

最后,我們分析一下,為什么 this.$nextTick 能夠獲取更新后的 DOM?

  1. // 我們使用 this.$nextTick 其實(shí)就是調(diào)用 nextTick 方法 
  2. Vue.prototype.$nextTick = function (fn: Function) { 
  3.   return nextTick(fn, this); 
  4. }; 

可以看到,調(diào)用 this.$nextTick 其實(shí)就是調(diào)用了圖中的 nextTick 方法,在異步隊(duì)列中執(zhí)行回調(diào)函數(shù)。根據(jù)先來后到原則,修改 Data 觸發(fā)的更新異步隊(duì)列會(huì)先得到執(zhí)行,執(zhí)行完成后就生成了新的 DOM ,接下來執(zhí)行 this.$nextTick 的回調(diào)函數(shù)時(shí),能獲取到更新后的 DOM 元素了。

由于 nextTick 只是單純通過 Promise 、SetTimeout 等方法模擬的異步任務(wù),所以也可以手動(dòng)執(zhí)行一個(gè)異步任務(wù),來實(shí)現(xiàn)和 this.$nextTick 相同的效果。

  1. this.message = "hello world"
  2. // 手動(dòng)執(zhí)行一個(gè)異步任務(wù),也能獲取最新的 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. }); 

思考與總結(jié)

本文從源碼的角度,介紹了 Vue 異步更新的原理,來簡(jiǎn)單回顧一下吧。

修改 Vue 中的 Data 時(shí),就會(huì)觸發(fā)所有和這個(gè) Data 相關(guān)的 Watcher 進(jìn)行更新。

首先,會(huì)將所有的 Watcher 加入隊(duì)列 Queue。

然后,調(diào)用 nextTick 方法,執(zhí)行異步任務(wù)。

在異步任務(wù)的回調(diào)中,對(duì) Queue 中的 Watcher 進(jìn)行排序,然后執(zhí)行對(duì)應(yīng)的 DOM 更新。

責(zé)任編輯:武曉燕 來源: 前端日志
相關(guān)推薦

2020-09-21 14:35:20

VuenextTick前端

2021-02-05 15:01:41

GitLinux命令

2021-06-09 10:29:23

Kafka架構(gòu)組件

2021-04-09 08:54:14

Kafka源碼架構(gòu)開發(fā)技術(shù)

2021-08-02 07:57:03

注冊(cè)Nacos源碼

2021-12-07 07:32:09

kafka架構(gòu)原理

2024-03-08 10:38:07

Vue響應(yīng)式數(shù)據(jù)

2024-10-30 10:06:51

2022-11-08 00:00:00

監(jiān)控系統(tǒng)Prometheus

2020-12-09 10:29:53

SSH加密數(shù)據(jù)安全

2020-11-30 07:54:46

ElasticSear開源分布式

2017-12-26 17:42:12

前端WebGLThree.js

2020-09-14 08:56:30

Vue模板

2010-02-04 10:17:38

Android應(yīng)用程序

2023-01-04 13:43:24

讀寫鎖AQS共享模式

2023-09-19 08:12:18

2021-05-19 09:29:52

VueAxios異步請(qǐng)求

2021-09-29 11:33:19

異步組件Vue 3

2021-02-09 09:51:58

異步傳遞數(shù)據(jù)

2023-03-13 17:18:09

OkHttp同步異步
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)