vue 源碼解析之虛擬Dom-render
vue 源碼解析 --虛擬Dom-render
instance/index.js
function 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 實例化執(zhí)行this._init, 執(zhí)行this.init方法中有initRender()
renderMixin
installRenderHelpers( 將一些渲染的工具函數(shù)放在Vue 原型上)
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
仔細看這個函數(shù), 在Vue中的官方文檔上這樣解釋
Vue 異步執(zhí)行 DOM 更新。只要觀察到數(shù)據(jù)變化,Vue 將開啟一個隊列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)改變。如果同一個 watcher 被多次觸發(fā),只會被推入到隊列中一次。這種在緩沖時去除重復(fù)數(shù)據(jù)對于避免不必要的計算和 DOM 操作上非常重要。然后,在下一個的事件循環(huán)“tick”中,Vue 刷新隊列并執(zhí)行實際 (已去重的) 工作。Vue 在內(nèi)部嘗試對異步隊列使用原生的 Promise.then 和MessageChannel,如果執(zhí)行環(huán)境不支持,會采用 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個參數(shù)(回調(diào)函數(shù)和執(zhí)行回調(diào)函數(shù)的上下文環(huán)境),如果沒有提供回調(diào)函數(shù),那么將返回promise對象。
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
這個flushCallbacks 是執(zhí)行callbacks里存儲的所有回調(diào)函數(shù)。
timerFunc 用來觸發(fā)執(zhí)行回調(diào)函數(shù)
先判斷是否原生支持promise,如果支持,則利用promise來觸發(fā)執(zhí)行回調(diào)函數(shù);
否則,如果支持MutationObserver,則實例化一個觀察者對象,觀察文本節(jié)點發(fā)生變化時,觸發(fā)執(zhí)行
所有回調(diào)函數(shù)。
如果都不支持,則利用setTimeout設(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 = true
MutationObserver是一個構(gòu)造器,接受一個callback參數(shù),用來處理節(jié)點變化的回調(diào)函數(shù),observe方法中options參數(shù)characterData:設(shè)置true,表示觀察目標數(shù)據(jù)的改變
_render函數(shù)
通過執(zhí)行 createElement 方法并返回的是 vnode,它是一個虛擬的 Node。
vnode = render.call(vm._renderProxy, vm.$createElement)
總結(jié)
以上所述是小編給大家介紹的vue 源碼解析之虛擬Dom-render,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
Vue使用babel-polyfill兼容IE解決白屏及語法報錯問題
這篇文章主要介紹了Vue使用babel-polyfill兼容IE解決白屏及語法報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
vue?perfect-scrollbar(特定框架里使用非該框架定制庫/插件)
這篇文章主要為大家介紹了vue?perfect-scrollbar在特定框架里使用一款并非為該框架定制的庫/插件如何實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪<BR>2023-05-05
解決Vue警告Write?operation?failed:computed?value?is?readonl
這篇文章主要給大家介紹了關(guān)于如何解決Vue警告Write?operation?failed:computed?value?is?readonly的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-03-03

