vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解
引言
nextTick在vue中是一個(gè)很重要的方法,在new Vue實(shí)例化的同步過(guò)程中,將一些需要異步處理的函數(shù)推到異步隊(duì)列中去,可以等new Vue所有的同步任務(wù)執(zhí)行完后,再執(zhí)行異步隊(duì)列中的函數(shù)。
1、vue中nextTick的使用場(chǎng)景
借用vue.js官網(wǎng)中例子:
Vue.component("example", { template: "<span>{{ message }}</span>", data: function() { return { message: "未更新" }; }, methods: { updateMessage: function() { this.message = "已更新"; console.log(this.$el.textContent); // => '未更新' this.$nextTick(function() { console.log(this.$el.textContent); // => '已更新' }); } } });
例子中顯示數(shù)據(jù)變化后直接訪問(wèn)節(jié)點(diǎn)內(nèi)容是'未更新',當(dāng)使用了this.$nextTick包裹后訪問(wèn)節(jié)點(diǎn)內(nèi)容是'已更新',可以看出如果需要拿到數(shù)據(jù)變化后的節(jié)點(diǎn),則需要使用this.nextTick,這就是nextTick的使用場(chǎng)景。
那么,$nextTick是從哪里定義的?
2、vue中nextTick在哪里定義
在vue源碼initGlobalAPI(Vue)過(guò)程中:
import { nextTick } from '../util/index' // ... Vue.nextTick = nextTick
3、vue中nextTick的實(shí)現(xiàn)原理
/* @flow */ /* globals MutationObserver */ import { noop } from 'shared/util' import { handleError } from './error' import { isIE, isIOS, isNative } from './env' export let isUsingMicroTask = false const callbacks = [] let pending = false function flushCallbacks () { pending = false const copies = callbacks.slice(0) callbacks.length = 0 for (let i = 0; i < copies.length; i++) { copies[i]() } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). let timerFunc // 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 next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { const p = Promise.resolve() timerFunc = () => { p.then(flushCallbacks) // 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) } isUsingMicroTask = true } else if (!isIE && 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, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) 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) } isUsingMicroTask = true } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Technically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = () => { setImmediate(flushCallbacks) } } else { // Fallback to setTimeout. timerFunc = () => { setTimeout(flushCallbacks, 0) } } export function nextTick (cb?: Function, ctx?: Object) { let _resolve callbacks.push(() => { if (cb) { try { cb.call(ctx) } catch (e) { handleError(e, ctx, 'nextTick') } } else if (_resolve) { _resolve(ctx) } }) if (!pending) { pending = true timerFunc() } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve }) } }
(1)callbacks的定義
在nextTick中首先在callbacks中推入進(jìn)行try {} catch (e) {}捕捉錯(cuò)誤的回調(diào)函數(shù)。
(2)timerFunc的定義
然后,如沒(méi)有在pengding狀態(tài)時(shí),將pending置為true,并執(zhí)行timerFunc函數(shù),這個(gè)函數(shù)依次根據(jù)當(dāng)前瀏覽器執(zhí)行環(huán)境中支不支持Promise、MutationObserver和setImmediate方法進(jìn)行賦值,如果都不支持,則使用setTimeout。
- 第一步,如果瀏覽器支持Promise,const p = Promise.resolve(),然后timerFunc中定義p.then(flushCallbacks),通過(guò)p.then(flushCallbacks)自執(zhí)行的能力來(lái)誘發(fā)flushCallbacks;
- 第二步,如果瀏覽器不支持Promise但支持MutationObserver,則其利用DOM屬性監(jiān)聽變化的能力,首先定義const observer = new MutationObserver(flushCallbacks),并監(jiān)聽const textNode = document.createTextNode(String(counter))的變化,timerFunc的執(zhí)行是通過(guò)修改textNode值來(lái)誘發(fā)flushCallbacks的執(zhí)行。
- 第三步,以上兩者都不滿足,但瀏覽器支持立即執(zhí)行函數(shù)setImmediate,則通過(guò)timerFunc = () => { setImmediate(flushCallbacks) }的方式來(lái)誘發(fā)flushCallbacks.
- 第四步,以上條件都不滿足的時(shí)候,則通過(guò)timerFunc = () => { setTimeout(flushCallbacks, 0) }將定時(shí)器的延遲時(shí)間設(shè)置為0進(jìn)行flushCallbacks的誘發(fā)。
以上四步中提到的的flushCallbacks函數(shù),其中pending = false表示同步任務(wù)已經(jīng)執(zhí)行結(jié)束,開始了異步隊(duì)列的執(zhí)行。const copies = callbacks.slice(0)進(jìn)行異步事件的淺拷貝,并將異步隊(duì)列數(shù)組callbacks清空,等待下一次異步隊(duì)列的推入。通過(guò)for (let i = 0; i < copies.length; i++) { copies[i]() }進(jìn)行當(dāng)前異步隊(duì)列中函數(shù)的執(zhí)行。
(3)cb未傳入的處理
最后,如果沒(méi)有傳入cb并且環(huán)境也支持Promise,return new Promise(resolve => { _resolve = resolve }),然后在執(zhí)行異步隊(duì)列中的函數(shù)的時(shí)候,直接執(zhí)行_resolve(ctx),為nextTick的使用提供了又一個(gè)方法Vue.nextTick().then(function () {// DOM 更新了})。
4、vue中nextTick的任務(wù)分類
在timerFunc的定義過(guò)程中,Promise和MutationObserver情況下,有一行代碼isUsingMicroTask = true表示當(dāng)前情況使用了微任務(wù)。nextTick的實(shí)現(xiàn)過(guò)程中也用到了宏任務(wù)setImmediate和setTimeout。
小結(jié)
可以感受到,nextTick異步隊(duì)列執(zhí)行是從最優(yōu)解到次優(yōu)解的一次降級(jí)處理,也是對(duì)于異步執(zhí)行兼容性的處理。
以上就是vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解的詳細(xì)內(nèi)容,更多關(guān)于vue2數(shù)據(jù)視圖變化nextTick的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue實(shí)現(xiàn)購(gòu)物車功能(親測(cè)可用)
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)購(gòu)物車功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04Vue中transition單個(gè)節(jié)點(diǎn)過(guò)渡與transition-group列表過(guò)渡全過(guò)程
這篇文章主要介紹了Vue中transition單個(gè)節(jié)點(diǎn)過(guò)渡與transition-group列表過(guò)渡全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04vue3利用keepAlive緩存頁(yè)面實(shí)例詳解
<keep-alive> 是一個(gè)抽象組件,它自身不會(huì)渲染一個(gè)DOM元素,也不會(huì)出現(xiàn)在組件的父組件鏈中,下面這篇文章主要給大家介紹了關(guān)于vue3利用keepAlive緩存頁(yè)面的相關(guān)資料,需要的朋友可以參考下2022-11-11Vue?data中隨意改一個(gè)屬性,視圖都會(huì)更新嗎?
這篇文章主要討論Vue?data中隨意改一個(gè)屬性,視圖都會(huì)更新嗎?下面來(lái)自面試官的問(wèn)題然后做i出的一個(gè)問(wèn)題總結(jié),具有一定的參考價(jià)值,需要的小伙伴可以參考一下2021-12-12vue實(shí)現(xiàn)多組關(guān)鍵詞對(duì)應(yīng)高亮顯示功能
最近小編遇到這樣的問(wèn)題,多組關(guān)鍵詞,這里實(shí)現(xiàn)了關(guān)鍵詞的背景色與匹配值的字體顏色值相同,下面通過(guò)定義關(guān)鍵詞匹配改變字體顏色,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2019-07-07