国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue 源碼解析之虛擬Dom-render

2024-05-06 15:35:27
字體:
供稿:網(wǎng)友

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 = true

MutationObserver是一個(gè)構(gòu)造器,接受一個(gè)callback參數(shù),用來處理節(jié)點(diǎn)變化的回調(diào)函數(shù),observe方法中options參數(shù)characterData:設(shè)置true,表示觀察目標(biāo)數(shù)據(jù)的改變

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 渑池县| 晋中市| 西乌珠穆沁旗| 屯留县| 客服| 宜丰县| 临汾市| 玉环县| 云浮市| 安徽省| 舟曲县| 安远县| 清镇市| 韶山市| 海安县| 莱西市| 兴国县| 桦川县| 垦利县| 镇沅| 云和县| 松桃| 宜良县| 中方县| 驻马店市| 濮阳市| 安庆市| 江津市| 如东县| 电白县| 文安县| 枝江市| 昌都县| 阿城市| 临湘市| 琼海市| 阜阳市| 榆林市| 朝阳县| 黎平县| 平阴县|