在項目中常常須要在視圖層當即顯示數據,而有時候因爲異步數據傳遞的緣由,在頁面上並不會當即顯示頁面,這時候就須要使用Vue提供的nextTick這個方法,其主要緣由是Vue的數據視圖是異步更新的,用官方的解釋就是:html
Vue 實現響應式並非數據發生變化以後 DOM 當即變化,而是按必定的策略進行 DOM 的更新。
其中說到的事件循環也是前端面試中常問到的一個點,本文不作具體展開,有興趣的同窗可參考這篇文章 一次弄懂Event Loop(完全解決此類面試問題)前端
[bug描述] 頁面上點擊重置後將模板視圖渲染會一個固定數據下的視圖vue
[bug分析] 點擊後須要當即顯示在頁面上,這是典型的nextTick須要應用的場景node
[解決方案] ios
此處還有一個坑就是對於數組類型的監聽是基於一個地址的,於是若是須要Vue的Watcher可以監視到就須要符合數組監聽的那幾種方法,這裏直接新建,至關於每次的地址都會發生變化,於是能夠監聽到git
async resetTemplate() { this.template = []; await this.$nextTick(function() { this.template = [ { week: '1', starttime: '00:00:00', endtime: '00:00:00' }, { week: '2', starttime: '00:00:00', endtime: '00:00:00' }, { week: '3', starttime: '00:00:00', endtime: '00:00:00' }, { week: '4', starttime: '00:00:00', endtime: '00:00:00' }, { week: '5', starttime: '00:00:00', endtime: '00:00:00' }, { week: '6', starttime: '00:00:00', endtime: '00:00:00' }, { week: '7', starttime: '00:00:00', endtime: '00:00:00' } ]; }); }
[bug描述] 頁面修改彈窗中的輸入框字段須要複寫進對應字段,利用Props傳遞數據進去後並不會直接修改數據面試
[bug分析] 此場景下數據是經過子組件emit給父組件,父組件獲取數據後經過props傳遞給彈窗,在v-model中獲取數據是異步的segmentfault
[解決方案] 數組
這是比較不常見的一種使用$nextTick去處理v-model異步數據傳遞的方法(ps: 關於emit/on的發佈訂閱相關的介紹,有興趣的同窗能夠看一下這篇文章 [vue發佈訂閱者模式$emit、$on](https://blog.csdn.net/qq_4277...,利用的是父組件的數據延遲到下一個tick去給子組件傳遞,子組件在對應頁面上及時渲染的方法,除了這種方法還有其餘方法,具體可參考這篇文章 詳解vue父組件傳遞props異步數據到子組件的問題app
edit(data) { this.isManu = true; let [content,pos] = data; this.manuPos = pos; this.form = content; this.$nextTick(function(){ this.$refs.deviceEdit.form.deviceid = content.deviceId; this.$refs.deviceEdit.form.devicename = content.deviceName; this.$refs.deviceEdit.form.devicebrand = content.deviceBrand; this.$refs.deviceEdit.form.devicegroup = content.deviceGroup; this.$refs.deviceEdit.form.mediatrans = content.mediaTrans; this.$refs.deviceEdit.form.cloudstorage = content.cloudStorage; this.$refs.deviceEdit.form.longitude = content.longitude; this.$refs.deviceEdit.form.latitude = content.latitude; this.$refs.deviceEdit.form.altitude = content.altitude; }) },
2.5以前的版本:
/** * Defer a task to execute it asynchronously. */ export const nextTick = (function () { const callbacks = [] let pending = false let timerFunc function nextTickHandler () { pending = false 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 */ if (typeof Promise !== 'undefined' && isNative(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 (!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 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 */ timerFunc = () => { setTimeout(nextTickHandler, 0) } } return function queueNextTick (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() } if (!cb && typeof Promise !== 'undefined') { return new Promise((resolve, reject) => { _resolve = resolve }) } } })()
2.5以後的版本
/* @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 }) } }
不一樣版本主要在於timeFunc的異步函數使用優先順序不一樣,2.5以後也有些許不一樣,但主要在於要不要暴露微任務函數和宏任務函數的問題(ps:上邊的2.5以後的版本是2.6.11)
2.5以前版本: Promise => MutationObserver => setTimeout2.5以後版本: setImmediate => MessageChannel => Promise => setTimeout
js的異步執行機制是前端同窗必須掌握的知識,其中nextTick就是其中一個很典型的表明,node中也有nextTick相關的方法,面試中也經常問到相關方法的實現,深入理解js的基礎方法和特性,對前端開發中避坑仍是頗有用處的,往往出現問題幾乎在全部的面試題中都有相關知識的展示,打好基礎永遠是一個工程師上升的堅實的基礎!
let callbacks = [] let pending = false function nextTick (cb) { callbacks.push(cb) if (!pending) { pending = true setTimeout(flushCallback, 0) } } function flushCallback () { pending = false let copies = callbacks.slice() callbacks.length = 0 copies.forEach(copy => { copy() }) }