欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue虛擬dom被創(chuàng)建的方法

 更新時(shí)間:2022年10月21日 09:06:33   作者:yyds2026  
這篇文章主要介紹了Vue虛擬dom是如何被創(chuàng)建的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

先來看生成虛擬dom的入口文件:

 ...
  import { parse } from './parser/index'
  import { optimize } from './optimizer'
  import { generate } from './codegen/index'
  ...
   const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  const code = generate(ast, options)
  ...

我們看到了AST經(jīng)過三輪加工,最終脫胎換骨成為render function code。那么我們這一章就來講AST的第三次試煉。入口文件./codegen/index

export function generate (
ast: ASTElement | void,
options: CompilerOptions
): CodegenResult {
const state = new CodegenState(options)
const code = ast ? genElement(ast, state) : '_c("div")'
return {
  render: `with(this){return $[code]}`,
  staticRenderFns: state.staticRenderFns
}
}

我們來看generate函數(shù)內(nèi)部構(gòu)造,返回render是一個(gè)with(this){return $[code]}包起來的一串東西,staticRenderFns是在編譯過程中會(huì)把那些不會(huì)變的靜態(tài)節(jié)點(diǎn)打上標(biāo)記,設(shè)置為true,然后在渲染階段單獨(dú)渲染。
那么genElement函數(shù)的作用是什么呢?

export function genElement (el: ASTElement, state: CodegenState): string {
  if (el.staticRoot && !el.staticProcessed) {
    return genStatic(el, state)
  } else if (el.once && !el.onceProcessed) {
    return genOnce(el, state)
  } else if (el.for && !el.forProcessed) {
    return genFor(el, state)
  } else if (el.if && !el.ifProcessed) {
    return genIf(el, state)
  } else if (el.tag === 'template' && !el.slotTarget) {
    return genChildren(el, state) || 'void 0'
  } else if (el.tag === 'slot') {
    return genSlot(el, state)
  } else {
    // component or element
    let code
    if (el.component) {
      code = genComponent(el.component, el, state)
    } else {
      const data = el.plain ? undefined : genData(el, state)

      const children = el.inlineTemplate ? null : genChildren(el, state, true)
      code = `_c('${el.tag}'${        data ? `,${data}` : '' // data      }${        children ? `,${children}` : '' // children      })`
    }
    // module transforms
    for (let i = 0; i < state.transforms.length; i++) {
      code = state.transforms[i](el, code)
    }
    return code
  }
}

我們可以看到有無限個(gè)if else在嵌套,而且once、for、if、tag就是Vue本身的屠特殊標(biāo)簽,并且最后有return code 那么就是拼接字符串。
那么我們來看一看生成的with(this){return $[code]}長啥樣:

<div id="app">
  <ul>
    <li v-for="item in items">
      itemid:{{item.id}}
    </li>
  </ul>
</div>

經(jīng)過compile之后轉(zhuǎn)化成:

with(this){
  return 
     _c('div',{
         attrs:{"id":"app"}
     },
     [_c('ul',_l((items),function(item){
       return _c('li',
                 [_v("\n      itemid:"+_s(item.id)+"\n    ")]
       )}
      )
     )]
   )}

到這里我們就把tamplate三次錘煉講完了,那么render function code 有了,那真正的渲染函數(shù)在哪呢?進(jìn)一步來揭曉:

return {
    ast, //AST模型
    render: code.render, //render函數(shù)字符串
    staticRenderFns: code.staticRenderFns //靜態(tài)節(jié)點(diǎn)render函數(shù)字符串
  }

我們暴露出去一個(gè)astrender、staticRenderFns分別為AST模型,render函數(shù)字符串,靜態(tài)的render函數(shù)字符串,那么我們的render函數(shù)在那里呢?
我們知道在Vue初始化的時(shí)候initRender:

  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)

該方法向vue上掛載了兩個(gè)方法,一個(gè)服務(wù)于用戶手寫的render函數(shù),一個(gè)則用于template模板。

export function renderMixin (Vue: Class<Component>) {
  // install runtime convenience helpers
  installRenderHelpers(Vue.prototype)

  Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this)
  }

  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options

    // reset _rendered flag on slots for duplicate slot check
    if (process.env.NODE_ENV !== 'production') {
      for (const key in vm.$slots) {
        // $flow-disable-line
        vm.$slots[key]._rendered = false
      }
    }

    if (_parentVnode) {
      vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
    }

    // set parent vnode. this allows render functions to have access
    // to the data on the placeholder node.
    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') {
        if (vm.$options.renderError) {
          try {
            vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
          } catch (e) {
            handleError(e, vm, `renderError`)
            vnode = vm._vnode
          }
        } else {
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
        warn(
          'Multiple root nodes returned from render function. Render function ' +
          'should return a single root node.',
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }
}

向vue原型上掛載了_render方法,該方法在mount的過程中會(huì)被調(diào)用生成一個(gè)vnode實(shí)例用于update對(duì)比生成一個(gè)新的dom對(duì)象并對(duì)原dom節(jié)點(diǎn)進(jìn)行替換,該方法將會(huì)拿到option上定義render方法:

new Vue({
    el:"#app",
    render(createElement){
        return createElement("div",{
            attr:{
                id:"app"
            }
        },this.message)
    },
    data(){
        return {
            message:"hello"
        }
    }
})

一種則是使用的template方式,但是該方法最終在mount的過程中通過調(diào)用compileToFunctions會(huì)被轉(zhuǎn)化render函數(shù),也就是說,最終供_render方法使用的實(shí)際上就是我們自定義的render函數(shù),在初始化render中會(huì)代理Vue實(shí)例vm._renderProxy,其實(shí)就是vue,那么vm.$createElement就是添加在Vue原型上的一個(gè)方法(initRender階段),所以就是createElement方法

/** * 創(chuàng)建vnode節(jié)點(diǎn), 本質(zhì)上是調(diào)_createElement方法, 這里做一層封裝, 來兼容更多情況 */
export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  // 根據(jù)normalizationType的不同, 后續(xù)處理children的方式也不同, 詳見core/vdom/helpers/normalzie-children.js
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}


export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode | Array<VNode> {
  // 如果節(jié)點(diǎn)的data已經(jīng)是響應(yīng)式, 即已有__ob__屬性, 直接返回空節(jié)點(diǎn)并發(fā)出警告
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid using observed data object as vnode data:' + ` ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }
  // 處理動(dòng)態(tài)組件
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  // 沒有tag字段的組件直接返回一個(gè)空節(jié)點(diǎn)
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // warn against non-primitive key
  // 檢查key是否是string or number
  if (process.env.NODE_ENV !== 'production' &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
  ) {
    if (!__WEEX__ || !('@binding' in data.key)) {
      warn(
        'Avoid using non-primitive value as key, ' +
        'use string/number value instead.',
        context
      )
    }
  }
  // support single function children as default scoped slot
  // 對(duì)于children數(shù)組的兩種處理方式, 詳見helper/normalize-children.js
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  /**   * 先對(duì)tag進(jìn)行判斷 如果是 string ,接著判斷是否是dom內(nèi)置的節(jié)點(diǎn),如果是則直接創(chuàng)建一個(gè)普通 VNode   * 如果是為已注冊的組件名,則通過 createComponent 創(chuàng)建一個(gè)組件類型的 VNode   * 否則創(chuàng)建一個(gè)未知的標(biāo)簽的 VNode   *    * 如果tag是Component類型, 通過createComponent創(chuàng)建一個(gè)節(jié)點(diǎn)   */
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }
  // 對(duì)vnode進(jìn)行標(biāo)準(zhǔn)化處理, 保證每次都返回一個(gè)標(biāo)準(zhǔn)格式的vnode
  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    if (isDef(ns)) applyNS(vnode, ns)
    if (isDef(data)) registerDeepBindings(data)
    return vnode
  } else {
    return createEmptyVNode()
  }
}

// 對(duì)每個(gè)children節(jié)點(diǎn)應(yīng)用命名空間
function applyNS (vnode, ns, force) {
  vnode.ns = ns
  if (vnode.tag === 'foreignObject') {
    // use default namespace inside foreignObject
    ns = undefined
    force = true
  }
  if (isDef(vnode.children)) {
    for (let i = 0, l = vnode.children.length; i < l; i++) {
      const child = vnode.children[i]
      if (isDef(child.tag) && (
        isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
        applyNS(child, ns, force)
      }
    }
  }
}

// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
// 對(duì)于style和class進(jìn)行深度遞歸綁定
function registerDeepBindings (data) {
  if (isObject(data.style)) {
    traverse(data.style)
  }
  if (isObject(data.class)) {
    traverse(data.class)
  }
}

其中在判斷ALWAYS_NORMALIZEnormalizationType時(shí)候,用戶手寫的ALWAYS_NORMALIZE一直是true,所以就會(huì)調(diào)用normalizeChildren(children)

export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}
  • 當(dāng)childre是子組件的時(shí)候就會(huì)扁平化
  • 當(dāng)children是基礎(chǔ)數(shù)據(jù)類型的時(shí)候,直接調(diào)用createTextNode函數(shù)變成文本節(jié)點(diǎn)
  • 當(dāng)children是數(shù)組的時(shí)候,會(huì)調(diào)用normalizeArrayChildren進(jìn)行格式化
    最后調(diào)用vnode = new VNode()生成一個(gè)vnode
    這一章講解了generate解析AST對(duì)象生成render function code在到虛擬VNode是怎么生成出來的,下一章講一個(gè)核心概念diff算法

到此這篇關(guān)于Vue虛擬dom是如何被創(chuàng)建的的文章就介紹到這了,更多相關(guān)Vue虛擬dom內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue項(xiàng)目實(shí)現(xiàn)點(diǎn)擊目標(biāo)區(qū)域之外可關(guān)閉(隱藏)目標(biāo)區(qū)域

    vue項(xiàng)目實(shí)現(xiàn)點(diǎn)擊目標(biāo)區(qū)域之外可關(guān)閉(隱藏)目標(biāo)區(qū)域

    這篇文章主要介紹了vue項(xiàng)目實(shí)現(xiàn)點(diǎn)擊目標(biāo)區(qū)域之外可關(guān)閉(隱藏)目標(biāo)區(qū)域,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Vue大屏數(shù)據(jù)展示示例

    Vue大屏數(shù)據(jù)展示示例

    公司的大數(shù)據(jù)工作組就需要通過數(shù)據(jù)大屏展示一些處理過后有價(jià)值的信息,本文主要介紹了Vue大屏數(shù)據(jù)展示示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • vue3?tailwindcss的使用教程

    vue3?tailwindcss的使用教程

    Tailwind是由Adam Wathan領(lǐng)導(dǎo)的TailwindLabs開發(fā)的 CSS 框架,這篇文章主要介紹了vue3?tailwindcss的使用,需要的朋友可以參考下
    2023-08-08
  • vant-ui框架的一個(gè)bug(解決切換后onload不觸發(fā))

    vant-ui框架的一個(gè)bug(解決切換后onload不觸發(fā))

    這篇文章主要介紹了vant-ui框架的一個(gè)bug(解決切換后onload不觸發(fā)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • 使用Vue.js創(chuàng)建一個(gè)時(shí)間跟蹤的單頁應(yīng)用

    使用Vue.js創(chuàng)建一個(gè)時(shí)間跟蹤的單頁應(yīng)用

    這篇文章主要介紹了使用Vue.js創(chuàng)建一個(gè)時(shí)間跟蹤的單頁應(yīng)用的相關(guān)資料,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2016-11-11
  • Django+Vue.js實(shí)現(xiàn)搜索功能

    Django+Vue.js實(shí)現(xiàn)搜索功能

    本文主要介紹了Django+Vue.js實(shí)現(xiàn)搜索功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-06-06
  • vue3使用reactive賦值后頁面不改變

    vue3使用reactive賦值后頁面不改變

    本文主要介紹了vue3使用reactive賦值后頁面不改變,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • ant?design?vue?pro?支持多頁簽?zāi)J絾栴}

    ant?design?vue?pro?支持多頁簽?zāi)J絾栴}

    這篇文章主要介紹了ant?design?vue?pro?支持多頁簽?zāi)J絾栴},具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • 淺談Vue3中watchEffect的具體用法

    淺談Vue3中watchEffect的具體用法

    watchEffect,它立即執(zhí)行傳入的一個(gè)函數(shù),同時(shí)響應(yīng)式追蹤其依賴,并在其依賴變更時(shí)重新運(yùn)行該函數(shù),本文主要介紹了Vue3中watchEffect的具體用法,感興趣的可以了解一下
    2022-05-05
  • vue如何實(shí)現(xiàn)對(duì)請(qǐng)求參數(shù)進(jìn)行簽名

    vue如何實(shí)現(xiàn)對(duì)請(qǐng)求參數(shù)進(jìn)行簽名

    這篇文章主要介紹了vue如何實(shí)現(xiàn)對(duì)請(qǐng)求參數(shù)進(jìn)行簽名問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01

最新評(píng)論