圖解 Vue 異步更新原理
本文轉(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 元素。
例如:
- <template>
- <div>
- <span id="text">{{ message }}</span>
- <button @click="changeData">
- changeData
- </button>
- </div>
- </template>
- <script>
- export default {
- data() {
- return {
- message: "hello",
- };
- },
- methods: {
- changeData() {
- this.message = "hello world";
- const textContent = document.getElementById("text").textContent;
- // 直接獲取,不是最新的
- console.log(textContent === "hello world"); // false
- // $nextTick 回調(diào)中,是最新的
- this.$nextTick(() => {
- const textContent = document.getElementById("text").textContent;
- console.warn(textContent === "hello world"); // true
- });
- },
- },
- };
- </script>
什么時(shí)候我們才能獲取到真正的 DOM 元素?
答:在 Vue 的 nextTick 回調(diào)中。
這一點(diǎn)在 Vue 官網(wǎng)有詳細(xì)的介紹,但你是否有想過,為什么 Vue 需要通過 nextTick 方法才能獲取最新的 DOM?
帶著這個(gè)疑問,我們直接看一下源碼。
- // 當(dāng)一個(gè) Data 更新時(shí),會(huì)依次執(zhí)行以下代碼
- // 1. 觸發(fā) Data.set
- // 2. 調(diào)用 dep.notify
- // 3. Dep 會(huì)遍歷所有相關(guān)的 Watcher 執(zhí)行 update 方法
- class Watcher {
- // 4. 執(zhí)行更新操作
- update() {
- queueWatcher(this);
- }
- }
- const queue = [];
- function queueWatcher(watcher: Watcher) {
- // 5. 將當(dāng)前 Watcher 添加到異步隊(duì)列
- queue.push(watcher);
- // 6. 執(zhí)行異步隊(duì)列,并傳入回調(diào)
- nextTick(flushSchedulerQueue);
- }
- // 更新視圖的具體方法
- function flushSchedulerQueue() {
- let watcher, id;
- // 排序,先渲染父節(jié)點(diǎn),再渲染子節(jié)點(diǎn)
- // 這樣可以避免不必要的子節(jié)點(diǎn)渲染,如:父節(jié)點(diǎn)中 v-if 為 false 的子節(jié)點(diǎn),就不用渲染了
- queue.sort((a, b) => a.id - b.id);
- // 遍歷所有 Watcher 進(jìn)行批量更新。
- for (index = 0; index < queue.length; index++) {
- watcher = queue[index];
- // 更新 DOM
- watcher.run();
- }
- }
根據(jù)上面的代碼,我們可以得出這樣一個(gè)流程圖:
圖中可以看到,Vue 在調(diào)用 Watcher 更新視圖時(shí),并不會(huì)直接進(jìn)行更新,而是把需要更新的 Watcher 加入到 Queue 隊(duì)列里,然后把具體的更新方法 flushSchedulerQueue 傳給 nextTick 進(jìn)行調(diào)用。
接下來,我們分析一下 nextTick。
- const callbacks = [];
- let timerFunc;
- function nextTick(cb?: Function, ctx?: Object) {
- let _resolve;
- // 1.將傳入的 flushSchedulerQueue 方法添加到回調(diào)數(shù)組
- callbacks.push(() => {
- cb.call(ctx);
- });
- // 2.執(zhí)行異步任務(wù)
- // 此方法會(huì)根據(jù)瀏覽器兼容性,選用不同的異步策略
- timerFunc();
- }
可以看到,nextTick 函數(shù)非常簡(jiǎn)單,它只是將傳入的 flushSchedulerQueue 添加到 callbacks 數(shù)組中,然后執(zhí)行了 timerFunc 方法。
接下來,我們分析一下 timerFunc 方法。
- let timerFunc;
- // 判斷是否兼容 Promise
- if (typeof Promise !== "undefined") {
- timerFunc = () => {
- Promise.resolve().then(flushCallbacks);
- };
- // 判斷是否兼容 MutationObserver
- // https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
- } else if (typeof MutationObserver !== "undefined") {
- 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);
- };
- // 判斷是否兼容 setImmediate
- // 該方法存在一些 IE 瀏覽器中
- } else if (typeof setImmediate !== "undefined") {
- // 這是一個(gè)宏任務(wù),但相比 setTimeout 要更好
- timerFunc = () => {
- setImmediate(flushCallbacks);
- };
- } else {
- // 如果以上方法都不知道,使用 setTimeout 0
- timerFunc = () => {
- setTimeout(flushCallbacks, 0);
- };
- }
- // 異步執(zhí)行完后,執(zhí)行所有的回調(diào)方法,也就是執(zhí)行 flushSchedulerQueue
- function flushCallbacks() {
- for (let i = 0; i < copies.length; i++) {
- callbacks[i]();
- }
- }
可以看到,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?
- // 我們使用 this.$nextTick 其實(shí)就是調(diào)用 nextTick 方法
- Vue.prototype.$nextTick = function (fn: Function) {
- return nextTick(fn, this);
- };
可以看到,調(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 相同的效果。
- this.message = "hello world";
- // 手動(dòng)執(zhí)行一個(gè)異步任務(wù),也能獲取最新的 DOM
- Promise.resolve().then(() => {
- const textContent = document.getElementById("text").textContent;
- console.log(textContent === "hello world"); // true
- });
- setTimeout(() => {
- const textContent = document.getElementById("text").textContent;
- console.log(textContent === "hello world"); // true
- });
思考與總結(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 更新。