2020-02-16

## 操作 DOM

在使用 vue.js 的時(shí)候,有時(shí)候因?yàn)橐恍┨囟ǖ臉I(yè)務(wù)場(chǎng)景,不得不去操作 DOM,比如這樣:

```html

<template>

? <div>

? ? <div ref="test">{{test}}</div>

? ? <button @click="handleClick">tet</button>

? </div>

</template>

```

```javascript

export default {

? ? data () {

? ? ? ? return {

? ? ? ? ? ? test: 'begin'

? ? ? ? };

? ? },

? ? methods () {

? ? ? ? handleClick () {

? ? ? ? ? ? this.test = 'end';

? ? ? ? ? ? console.log(this.$refs.test.innerText);//打印“begin”

? ? ? ? }

? ? }

}

```

打印的結(jié)果是 begin,為什么我們明明已經(jīng)將 test 設(shè)置成了“end”,獲取真實(shí) DOM 節(jié)點(diǎn)的 innerText 卻沒有得到我們預(yù)期中的“end”,而是得到之前的值“begin”呢?

## Watcher 隊(duì)列

帶著疑問,我們找到了 Vue.js 源碼的 Watch 實(shí)現(xiàn)。當(dāng)某個(gè)響應(yīng)式數(shù)據(jù)發(fā)生變化的時(shí)候,它的 setter 函數(shù)會(huì)通知閉包中的 Dep,Dep 則會(huì)調(diào)用它管理的所有 Watch 對(duì)象。觸發(fā) Watch 對(duì)象的 update 實(shí)現(xiàn)。我們來看一下 update 的實(shí)現(xiàn)。

```javascript

update () {

? ? /* istanbul ignore else */

? ? if (this.lazy) {

? ? ? ? this.dirty = true

? ? } else if (this.sync) {

? ? ? ? /*同步則執(zhí)行run直接渲染視圖*/

? ? ? ? this.run()

? ? } else {

? ? ? ? /*異步推送到觀察者隊(duì)列中,下一個(gè)tick時(shí)調(diào)用。*/

? ? ? ? queueWatcher(this)

? ? }

}

```

我們發(fā)現(xiàn) Vue.js 默認(rèn)是使用[異步執(zhí)行 DOM 更新](https://cn.vuejs.org/v2/guide/reactivity.html#異步更新隊(duì)列)。

當(dāng)異步執(zhí)行 update 的時(shí)候,會(huì)調(diào)用 queueWatcher 函數(shù)。

```javascript

/*將一個(gè)觀察者對(duì)象push進(jìn)觀察者隊(duì)列,在隊(duì)列中已經(jīng)存在相同的id則該觀察者對(duì)象將被跳過,除非它是在隊(duì)列被刷新時(shí)推送*/

export function queueWatcher(watcher: Watcher) {

? /*獲取watcher的id*/

? const id = watcher.id;

? /*檢驗(yàn)id是否存在,已經(jīng)存在則直接跳過,不存在則標(biāo)記哈希表has,用于下次檢驗(yàn)*/

? if (has[id] == null) {

? ? has[id] = true;

? ? if (!flushing) {

? ? ? /*如果沒有flush掉,直接push到隊(duì)列中即可*/

? ? ? queue.push(watcher);

? ? } else {

? ? ? // if already flushing, splice the watcher based on its id

? ? ? // if already past its id, it will be run next immediately.

? ? ? let i = queue.length - 1;

? ? ? while (i >= 0 && queue[i].id > watcher.id) {

? ? ? ? i--;

? ? ? }

? ? ? queue.splice(Math.max(i, index) + 1, 0, watcher);

? ? }

? ? // queue the flush

? ? if (!waiting) {

? ? ? waiting = true;

? ? ? nextTick(flushSchedulerQueue);

? ? }

? }

}

```

查看 queueWatcher 的源碼我們發(fā)現(xiàn),Watch 對(duì)象并不是立即更新視圖,而是被 push 進(jìn)了一個(gè)隊(duì)列 queue,此時(shí)狀態(tài)處于 waiting 的狀態(tài),這時(shí)候會(huì)繼續(xù)會(huì)有 Watch 對(duì)象被 push 進(jìn)這個(gè)隊(duì)列 queue,等到下一個(gè) tick 運(yùn)行時(shí),這些 Watch 對(duì)象才會(huì)被遍歷取出,更新視圖。同時(shí),id 重復(fù)的 Watcher 不會(huì)被多次加入到 queue 中去,因?yàn)樵谧罱K渲染時(shí),我們只需要關(guān)心數(shù)據(jù)的最終結(jié)果。

那么,什么是下一個(gè) tick?

## nextTick

vue.js 提供了一個(gè)[nextTick](https://cn.vuejs.org/v2/api/#Vue-nextTick)函數(shù),其實(shí)也就是上面調(diào)用的 nextTick。

nextTick 的實(shí)現(xiàn)比較簡(jiǎn)單,執(zhí)行的目的是在 microtask 或者 task 中推入一個(gè) function,在當(dāng)前棧執(zhí)行完畢(也許還會(huì)有一些排在前面的需要執(zhí)行的任務(wù))以后執(zhí)行 nextTick 傳入的 function,看一下源碼:

```javascript

/**

* Defer a task to execute it asynchronously.

*/

/*

? ? 延遲一個(gè)任務(wù)使其異步執(zhí)行,在下一個(gè)tick時(shí)執(zhí)行,一個(gè)立即執(zhí)行函數(shù),返回一個(gè)function

? ? 這個(gè)函數(shù)的作用是在task或者microtask中推入一個(gè)timerFunc,在當(dāng)前調(diào)用棧執(zhí)行完以后以此執(zhí)行直到執(zhí)行到timerFunc

? ? 目的是延遲到當(dāng)前調(diào)用棧執(zhí)行完以后執(zhí)行

*/

export const nextTick = (function() {

? /*存放異步執(zhí)行的回調(diào)*/

? const callbacks = [];

? /*一個(gè)標(biāo)記位,如果已經(jīng)有timerFunc被推送到任務(wù)隊(duì)列中去則不需要重復(fù)推送*/

? let pending = false;

? /*一個(gè)函數(shù)指針,指向函數(shù)將被推送到任務(wù)隊(duì)列中,等到主線程任務(wù)執(zhí)行完時(shí),任務(wù)隊(duì)列中的timerFunc被調(diào)用*/

? let timerFunc;

? /*下一個(gè)tick時(shí)的回調(diào)*/

? function nextTickHandler() {

? ? /*一個(gè)標(biāo)記位,標(biāo)記等待狀態(tài)(即函數(shù)已經(jīng)被推入任務(wù)隊(duì)列或者主線程,已經(jīng)在等待當(dāng)前棧執(zhí)行完畢去執(zhí)行),這樣就不需要在push多個(gè)回調(diào)到callbacks時(shí)將timerFunc多次推入任務(wù)隊(duì)列或者主線程*/

? ? pending = false;

? ? /*執(zhí)行所有callback*/

? ? const copies = callbacks.slice(0);

? ? callbacks.length = 0;

? ? for (let i = 0; i < copies.length; i++) {

? ? ? copies[i]();

? ? }

? }

? // 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 if */

? /*

? ? 這里解釋一下,一共有Promise、MutationObserver以及setTimeout三種嘗試得到timerFunc的方法

? ? 優(yōu)先使用Promise,在Promise不存在的情況下使用MutationObserver,這兩個(gè)方法都會(huì)在microtask中執(zhí)行,會(huì)比setTimeout更早執(zhí)行,所以優(yōu)先使用。

? ? 如果上述兩種方法都不支持的環(huán)境則會(huì)使用setTimeout,在task尾部推入這個(gè)函數(shù),等待調(diào)用執(zhí)行。

? ? 參考:https://www.zhihu.com/question/55364497

? */

? if (typeof Promise !== "undefined" && isNative(Promise)) {

? ? /*使用Promise*/

? ? var p = Promise.resolve();

? ? var logError = err => {

? ? ? console.error(err);

? ? };

? ? timerFunc = () => {

? ? ? p.then(nextTickHandler).catch(logError);

? ? ? // 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 (

? ? 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 IE11, iOS7, Android 4.4

? ? /*新建一個(gè)textNode的DOM對(duì)象,用MutationObserver綁定該DOM并指定回調(diào)函數(shù),在DOM變化的時(shí)候則會(huì)觸發(fā)回調(diào),該回調(diào)會(huì)進(jìn)入主線程(比任務(wù)隊(duì)列優(yōu)先執(zhí)行),即textNode.data = String(counter)時(shí)便會(huì)觸發(fā)回調(diào)*/

? ? var counter = 1;

? ? var observer = new MutationObserver(nextTickHandler);

? ? var textNode = document.createTextNode(String(counter));

? ? observer.observe(textNode, {

? ? ? characterData: true

? ? });

? ? timerFunc = () => {

? ? ? counter = (counter + 1) % 2;

? ? ? textNode.data = String(counter);

? ? };

? } else {

? ? // fallback to setTimeout

? ? /* istanbul ignore next */

? ? /*使用setTimeout將回調(diào)推入任務(wù)隊(duì)列尾部*/

? ? timerFunc = () => {

? ? ? setTimeout(nextTickHandler, 0);

? ? };

? }

? /*

? ? 推送到隊(duì)列中下一個(gè)tick時(shí)執(zhí)行

? ? cb 回調(diào)函數(shù)

? ? ctx 上下文

? */

? return function queueNextTick(cb?: Function, ctx?: Object) {

? ? let _resolve;

? ? /*cb存到callbacks中*/

? ? callbacks.push(() => {

? ? ? if (cb) {

? ? ? ? try {

? ? ? ? ? cb.call(ctx);

? ? ? ? } catch (e) {

? ? ? ? ? handleError(e, ctx, "nextTick");

? ? ? ? }

? ? ? } else if (_resolve) {

? ? ? ? _resolve(ctx);

? ? ? }

? ? });

? ? if (!pending) {

? ? ? pending = true;

? ? ? timerFunc();

? ? }

? ? if (!cb && typeof Promise !== "undefined") {

? ? ? return new Promise((resolve, reject) => {

? ? ? ? _resolve = resolve;

? ? ? });

? ? }

? };

})();

```

它是一個(gè)立即執(zhí)行函數(shù),返回一個(gè) queueNextTick 接口。

傳入的 cb 會(huì)被 push 進(jìn) callbacks 中存放起來,然后執(zhí)行 timerFunc(pending 是一個(gè)狀態(tài)標(biāo)記,保證 timerFunc 在下一個(gè) tick 之前只執(zhí)行一次)。

timerFunc 是什么?

看了源碼發(fā)現(xiàn) timerFunc 會(huì)檢測(cè)當(dāng)前環(huán)境而不同實(shí)現(xiàn),其實(shí)就是按照 Promise,MutationObserver,setTimeout 優(yōu)先級(jí),哪個(gè)存在使用哪個(gè),最不濟(jì)的環(huán)境下使用 setTimeout。

這里解釋一下,一共有 Promise、MutationObserver 以及 setTimeout 三種嘗試得到 timerFunc 的方法。

優(yōu)先使用 Promise,在 Promise 不存在的情況下使用 MutationObserver,這兩個(gè)方法的回調(diào)函數(shù)都會(huì)在 microtask 中執(zhí)行,它們會(huì)比 setTimeout 更早執(zhí)行,所以優(yōu)先使用。

如果上述兩種方法都不支持的環(huán)境則會(huì)使用 setTimeout,在 task 尾部推入這個(gè)函數(shù),等待調(diào)用執(zhí)行。

為什么要優(yōu)先使用 microtask?我在顧軼靈在知乎的回答中學(xué)習(xí)到:

```

JS 的 event loop 執(zhí)行時(shí)會(huì)區(qū)分 task 和 microtask,引擎在每個(gè) task 執(zhí)行完畢,從隊(duì)列中取下一個(gè) task 來執(zhí)行之前,會(huì)先執(zhí)行完所有 microtask 隊(duì)列中的 microtask。

setTimeout 回調(diào)會(huì)被分配到一個(gè)新的 task 中執(zhí)行,而 Promise 的 resolver、MutationObserver 的回調(diào)都會(huì)被安排到一個(gè)新的 microtask 中執(zhí)行,會(huì)比 setTimeout 產(chǎn)生的 task 先執(zhí)行。

要?jiǎng)?chuàng)建一個(gè)新的 microtask,優(yōu)先使用 Promise,如果瀏覽器不支持,再嘗試 MutationObserver。

實(shí)在不行,只能用 setTimeout 創(chuàng)建 task 了。

為啥要用 microtask?

根據(jù) HTML Standard,在每個(gè) task 運(yùn)行完以后,UI 都會(huì)重渲染,那么在 microtask 中就完成數(shù)據(jù)更新,當(dāng)前 task 結(jié)束就可以得到最新的 UI 了。

反之如果新建一個(gè) task 來做數(shù)據(jù)更新,那么渲染就會(huì)進(jìn)行兩次。

參考顧軼靈知乎的回答:https://www.zhihu.com/question/55364497/answer/144215284

```

首先是 Promise,Promise.resolve().then()可以在 microtask 中加入它的回調(diào),

MutationObserver 新建一個(gè) textNode 的 DOM 對(duì)象,用 MutationObserver 綁定該 DOM 并指定回調(diào)函數(shù),在 DOM 變化的時(shí)候則會(huì)觸發(fā)回調(diào),該回調(diào)會(huì)進(jìn)入 microtask,即 textNode.data = String(counter)時(shí)便會(huì)加入該回調(diào)。

setTimeout 是最后的一種備選方案,它會(huì)將回調(diào)函數(shù)加入 task 中,等到執(zhí)行。

綜上,nextTick 的目的就是產(chǎn)生一個(gè)回調(diào)函數(shù)加入 task 或者 microtask 中,當(dāng)前棧執(zhí)行完以后(可能中間還有別的排在前面的函數(shù))調(diào)用該回調(diào)函數(shù),起到了異步觸發(fā)(即下一個(gè) tick 時(shí)觸發(fā))的目的。

## flushSchedulerQueue

```javascript

/*Github:https://github.com/answershuto*/

/**

* Flush both queues and run the watchers.

*/

/*nextTick的回調(diào)函數(shù),在下一個(gè)tick時(shí)flush掉兩個(gè)隊(duì)列同時(shí)運(yùn)行watchers*/

function flushSchedulerQueue() {

? flushing = true;

? let watcher, id;

? // Sort queue before flush.

? // This ensures that:

? // 1. Components are updated from parent to child. (because parent is always

? //? ? created before the child)

? // 2. A component's user watchers are run before its render watcher (because

? //? ? user watchers are created before the render watcher)

? // 3. If a component is destroyed during a parent component's watcher run,

? //? ? its watchers can be skipped.

? /*

? ? 給queue排序,這樣做可以保證:

? ? 1.組件更新的順序是從父組件到子組件的順序,因?yàn)楦附M件總是比子組件先創(chuàng)建。

? ? 2.一個(gè)組件的user watchers比render watcher先運(yùn)行,因?yàn)閡ser watchers往往比render watcher更早創(chuàng)建

? ? 3.如果一個(gè)組件在父組件watcher運(yùn)行期間被銷毀,它的watcher執(zhí)行將被跳過。

? */

? queue.sort((a, b) => a.id - b.id);

? // do not cache length because more watchers might be pushed

? // as we run existing watchers

? /*這里不用index = queue.length;index > 0; index--的方式寫是因?yàn)椴灰獙ength進(jìn)行緩存,因?yàn)樵趫?zhí)行處理現(xiàn)有watcher對(duì)象期間,更多的watcher對(duì)象可能會(huì)被push進(jìn)queue*/

? for (index = 0; index < queue.length; index++) {

? ? watcher = queue[index];

? ? id = watcher.id;

? ? /*將has的標(biāo)記刪除*/

? ? has[id] = null;

? ? /*執(zhí)行watcher*/

? ? watcher.run();

? ? // in dev build, check and stop circular updates.

? ? /*

? ? ? 在測(cè)試環(huán)境中,檢測(cè)watch是否在死循環(huán)中

? ? ? 比如這樣一種情況

? ? ? watch: {

? ? ? ? test () {

? ? ? ? ? this.test++;

? ? ? ? }

? ? ? }

? ? ? 持續(xù)執(zhí)行了一百次watch代表可能存在死循環(huán)

? ? */

? ? if (process.env.NODE_ENV !== "production" && has[id] != null) {

? ? ? circular[id] = (circular[id] || 0) + 1;

? ? ? if (circular[id] > MAX_UPDATE_COUNT) {

? ? ? ? warn(

? ? ? ? ? "You may have an infinite update loop " +

? ? ? ? ? ? (watcher.user

? ? ? ? ? ? ? ? `in watcher with expression "${watcher.expression}"`

? ? ? ? ? ? ? : `in a component render function.`),

? ? ? ? ? watcher.vm

? ? ? ? );

? ? ? ? break;

? ? ? }

? ? }

? }

? // keep copies of post queues before resetting state

? /**/

? /*得到隊(duì)列的拷貝*/

? const activatedQueue = activatedChildren.slice();

? const updatedQueue = queue.slice();

? /*重置調(diào)度者的狀態(tài)*/

? resetSchedulerState();

? // call component updated and activated hooks

? /*使子組件狀態(tài)都改編成active同時(shí)調(diào)用activated鉤子*/

? callActivatedHooks(activatedQueue);

? /*調(diào)用updated鉤子*/

? callUpdateHooks(updatedQueue);

? // devtool hook

? /* istanbul ignore if */

? if (devtools && config.devtools) {

? ? devtools.emit("flush");

? }

}

```

flushSchedulerQueue 是下一個(gè) tick 時(shí)的回調(diào)函數(shù),主要目的是執(zhí)行 Watcher 的 run 函數(shù),用來更新視圖

## 為什么要異步更新視圖

來看一下下面這一段代碼

```html

<template>

? <div>

? ? <div>{{test}}</div>

? </div>

</template>

```

```javascript

export default {

? data() {

? ? return {

? ? ? test: 0

? ? };

? },

? mounted() {

? ? for (let i = 0; i < 1000; i++) {

? ? ? this.test++;

? ? }

? }

};

```

現(xiàn)在有這樣的一種情況,mounted 的時(shí)候 test 的值會(huì)被++循環(huán)執(zhí)行 1000 次。

每次++時(shí),都會(huì)根據(jù)響應(yīng)式觸發(fā) setter->Dep->Watcher->update->patch。

如果這時(shí)候沒有異步更新視圖,那么每次++都會(huì)直接操作 DOM 更新視圖,這是非常消耗性能的。

所以 Vue.js 實(shí)現(xiàn)了一個(gè) queue 隊(duì)列,在下一個(gè) tick 的時(shí)候會(huì)統(tǒng)一執(zhí)行 queue 中 Watcher 的 run。同時(shí),擁有相同 id 的 Watcher 不會(huì)被重復(fù)加入到該 queue 中去,所以不會(huì)執(zhí)行 1000 次 Watcher 的 run。最終更新視圖只會(huì)直接將 test 對(duì)應(yīng)的 DOM 的 0 變成 1000。

保證更新視圖操作 DOM 的動(dòng)作是在當(dāng)前棧執(zhí)行完以后下一個(gè) tick 的時(shí)候調(diào)用,大大優(yōu)化了性能。

## 訪問真實(shí) DOM 節(jié)點(diǎn)更新后的數(shù)據(jù)

所以我們需要在修改 data 中的數(shù)據(jù)后訪問真實(shí)的 DOM 節(jié)點(diǎn)更新后的數(shù)據(jù),只需要這樣,我們把文章第一個(gè)例子進(jìn)行修改。

```html

<template>

? <div>

? ? <div ref="test">{{test}}</div>

? ? <button @click="handleClick">tet</button>

? </div>

</template>

```

```javascript

export default {

? ? data () {

? ? ? ? return {

? ? ? ? ? ? test: 'begin'

? ? ? ? };

? ? },

? ? methods () {

? ? ? ? handleClick () {

? ? ? ? ? ? this.test = 'end';

? ? ? ? ? ? this.$nextTick(() => {

? ? ? ? ? ? ? ? console.log(this.$refs.test.innerText);//打印"end"

? ? ? ? ? ? });

? ? ? ? ? ? console.log(this.$refs.test.innerText);//打印“begin”

? ? ? ? }

? ? }

}

```

使用 Vue.js 的 global API 的\$nextTick 方法,即可在回調(diào)中獲取已經(jīng)更新好的 DOM 實(shí)例了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容