vue 源碼解析 --虛擬Dom-render
instance/index.jsfunction Vue (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options)}renderMixin(Vue)初始化先執(zhí)行了 renderMixin 方法, Vue 實(shí)例化執(zhí)行this._init, 執(zhí)行this.init方法中有initRender()
renderMixininstallRenderHelpers( 將一些渲染的工具函數(shù)放在Vue 原型上)Vue.prototype.$nextTick = function (fn: Function) { return nextTick(fn, this) }仔細(xì)看這個(gè)函數(shù), 在Vue中的官方文檔上這樣解釋
Vue 異步執(zhí)行 DOM 更新。只要觀察到數(shù)據(jù)變化,Vue 將開啟一個(gè)隊(duì)列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)改變。如果同一個(gè) watcher 被多次觸發(fā),只會(huì)被推入到隊(duì)列中一次。這種在緩沖時(shí)去除重復(fù)數(shù)據(jù)對(duì)于避免不必要的計(jì)算和 DOM 操作上非常重要。然后,在下一個(gè)的事件循環(huán)“tick”中,Vue 刷新隊(duì)列并執(zhí)行實(shí)際 (已去重的) 工作。Vue 在內(nèi)部嘗試對(duì)異步隊(duì)列使用原生的 Promise.then 和MessageChannel,如果執(zhí)行環(huán)境不支持,會(huì)采用 setTimeout(fn, 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 }) }}Vue.nextTick用于延遲執(zhí)行一段代碼,它接受2個(gè)參數(shù)(回調(diào)函數(shù)和執(zhí)行回調(diào)函數(shù)的上下文環(huán)境),如果沒有提供回調(diào)函數(shù),那么將返回promise對(duì)象。
function flushCallbacks () { pending = false const copies = callbacks.slice(0) callbacks.length = 0 for (let i = 0; i < copies.length; i++) { copies[i]() }}這個(gè)flushCallbacks 是執(zhí)行callbacks里存儲(chǔ)的所有回調(diào)函數(shù)。
timerFunc 用來觸發(fā)執(zhí)行回調(diào)函數(shù)
先判斷是否原生支持promise,如果支持,則利用promise來觸發(fā)執(zhí)行回調(diào)函數(shù);
否則,如果支持MutationObserver,則實(shí)例化一個(gè)觀察者對(duì)象,觀察文本節(jié)點(diǎn)發(fā)生變化時(shí),觸發(fā)執(zhí)行
所有回調(diào)函數(shù)。
如果都不支持,則利用setTimeout設(shè)置延時(shí)為0。
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 = trueMutationObserver是一個(gè)構(gòu)造器,接受一個(gè)callback參數(shù),用來處理節(jié)點(diǎn)變化的回調(diào)函數(shù),observe方法中options參數(shù)characterData:設(shè)置true,表示觀察目標(biāo)數(shù)據(jù)的改變
新聞熱點(diǎn)
疑難解答
圖片精選