vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解
引言
nextTick在vue中是一個很重要的方法,在new Vue實(shí)例化的同步過程中,將一些需要異步處理的函數(shù)推到異步隊列中去,可以等new Vue所有的同步任務(wù)執(zhí)行完后,再執(zhí)行異步隊列中的函數(shù)。
1、vue中nextTick的使用場景
借用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ù)變化后直接訪問節(jié)點(diǎn)內(nèi)容是'未更新',當(dāng)使用了this.$nextTick包裹后訪問節(jié)點(diǎn)內(nèi)容是'已更新',可以看出如果需要拿到數(shù)據(jù)變化后的節(jié)點(diǎn),則需要使用this.nextTick,這就是nextTick的使用場景。
那么,$nextTick是從哪里定義的?
2、vue中nextTick在哪里定義
在vue源碼initGlobalAPI(Vue)過程中:
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) {}捕捉錯誤的回調(diào)函數(shù)。
(2)timerFunc的定義
然后,如沒有在pengding狀態(tài)時,將pending置為true,并執(zhí)行timerFunc函數(shù),這個函數(shù)依次根據(jù)當(dāng)前瀏覽器執(zhí)行環(huán)境中支不支持Promise、MutationObserver和setImmediate方法進(jìn)行賦值,如果都不支持,則使用setTimeout。
- 第一步,如果瀏覽器支持Promise,const p = Promise.resolve(),然后timerFunc中定義p.then(flushCallbacks),通過p.then(flushCallbacks)自執(zhí)行的能力來誘發(fā)flushCallbacks;
- 第二步,如果瀏覽器不支持Promise但支持MutationObserver,則其利用DOM屬性監(jiān)聽變化的能力,首先定義const observer = new MutationObserver(flushCallbacks),并監(jiān)聽const textNode = document.createTextNode(String(counter))的變化,timerFunc的執(zhí)行是通過修改textNode值來誘發(fā)flushCallbacks的執(zhí)行。
- 第三步,以上兩者都不滿足,但瀏覽器支持立即執(zhí)行函數(shù)setImmediate,則通過timerFunc = () => { setImmediate(flushCallbacks) }的方式來誘發(fā)flushCallbacks.
- 第四步,以上條件都不滿足的時候,則通過timerFunc = () => { setTimeout(flushCallbacks, 0) }將定時器的延遲時間設(shè)置為0進(jìn)行flushCallbacks的誘發(fā)。
以上四步中提到的的flushCallbacks函數(shù),其中pending = false表示同步任務(wù)已經(jīng)執(zhí)行結(jié)束,開始了異步隊列的執(zhí)行。const copies = callbacks.slice(0)進(jìn)行異步事件的淺拷貝,并將異步隊列數(shù)組callbacks清空,等待下一次異步隊列的推入。通過for (let i = 0; i < copies.length; i++) { copies[i]() }進(jìn)行當(dāng)前異步隊列中函數(shù)的執(zhí)行。
(3)cb未傳入的處理
最后,如果沒有傳入cb并且環(huán)境也支持Promise,return new Promise(resolve => { _resolve = resolve }),然后在執(zhí)行異步隊列中的函數(shù)的時候,直接執(zhí)行_resolve(ctx),為nextTick的使用提供了又一個方法Vue.nextTick().then(function () {// DOM 更新了})。
4、vue中nextTick的任務(wù)分類
在timerFunc的定義過程中,Promise和MutationObserver情況下,有一行代碼isUsingMicroTask = true表示當(dāng)前情況使用了微任務(wù)。nextTick的實(shí)現(xiàn)過程中也用到了宏任務(wù)setImmediate和setTimeout。
小結(jié)
可以感受到,nextTick異步隊列執(zhí)行是從最優(yōu)解到次優(yōu)解的一次降級處理,也是對于異步執(zhí)行兼容性的處理。
以上就是vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解的詳細(xì)內(nèi)容,更多關(guān)于vue2數(shù)據(jù)視圖變化nextTick的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue中transition單個節(jié)點(diǎn)過渡與transition-group列表過渡全過程
這篇文章主要介紹了Vue中transition單個節(jié)點(diǎn)過渡與transition-group列表過渡全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04vue實(shí)現(xiàn)多組關(guān)鍵詞對應(yīng)高亮顯示功能
最近小編遇到這樣的問題,多組關(guān)鍵詞,這里實(shí)現(xiàn)了關(guān)鍵詞的背景色與匹配值的字體顏色值相同,下面通過定義關(guān)鍵詞匹配改變字體顏色,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2019-07-07