說說VNode節點(Vue.js實現) 原 薦

寫在前面

因爲對Vue.js很感興趣,而且平時工作的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並做了總結與輸出。 文章的原地址:https://github.com/answershuto/learnVue。 在學習過程中,爲Vue加上了中文的註釋https://github.com/answershuto/learnVue/tree/master/vue-src,希望可以對其他想學習Vue源碼的小夥伴有所幫助。 可能會有理解存在偏差的地方,歡迎提issue指出,共同學習,共同進步。

抽象Dom樹

在刀耕火種的年代,我們需要在各個事件方法中直接操作Dom來達到修改視圖的目的。但是當應用一大就會變得難以維護。

那我們是不是可以把真實Dom樹抽象成一棵以javascript對象構成的抽象樹,在修改抽象樹數據後將抽象樹轉化成真實Dom重繪到頁面上呢?於是虛擬Dom出現了,它是真實Dom的一層抽象,用屬性描述真實Dom的各個特性。當它發生變化的時候,就會去修改視圖。

但是這樣的javascript操作Dom進行重繪整個視圖層是相當消耗性能的,我們是不是可以每次只更新它的修改呢?所以Vue.js將Dom抽象成一個以javascript對象爲節點的虛擬Dom樹,以VNode節點模擬真實Dom,可以對這顆抽象樹進行創建節點、刪除節點以及修改節點等操作,在這過程中都不需要操作真實Dom,只需要操作javascript對象,大大提升了性能。修改以後經過diff算法得出一些需要修改的最小單位,再將這些小單位的視圖進行更新。這樣做減少了很多不需要的Dom操作,大大提高了性能。

Vue就使用了這樣的抽象節點VNode,它是對真實Dom的一層抽象,而不依賴某個平臺,它可以是瀏覽器平臺,也可以是weex,甚至是node平臺也可以對這樣一棵抽象Dom樹進行創建刪除修改等操作,這也爲前後端同構提供了可能。

VNode基類

先來看一下Vue.js源碼中對VNode類的定義。

export default class VNode {
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; // rendered in this component's scope
  functionalContext: Component | void; // only for functional component root nodes
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void; // component instance
  parent: VNode | void; // component placeholder node
  raw: boolean; // contains raw HTML? (server only)
  isStatic: boolean; // hoisted static node
  isRootInsert: boolean; // necessary for enter transition check
  isComment: boolean; // empty comment placeholder?
  isCloned: boolean; // is a cloned node?
  isOnce: boolean; // is a v-once node?

  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions
  ) {
    /*當前節點的標籤名*/
    this.tag = tag
    /*當前節點對應的對象,包含了具體的一些數據信息,是一個VNodeData類型,可以參考VNodeData類型中的數據信息*/
    this.data = data
    /*當前節點的子節點,是一個數組*/
    this.children = children
    /*當前節點的文本*/
    this.text = text
    /*當前虛擬節點對應的真實dom節點*/
    this.elm = elm
    /*當前節點的名字空間*/
    this.ns = undefined
    /*編譯作用域*/
    this.context = context
    /*函數化組件作用域*/
    this.functionalContext = undefined
    /*節點的key屬性,被當作節點的標誌,用以優化*/
    this.key = data && data.key
    /*組件的option選項*/
    this.componentOptions = componentOptions
    /*當前節點對應的組件的實例*/
    this.componentInstance = undefined
    /*當前節點的父節點*/
    this.parent = undefined
    /*簡而言之就是是否爲原生HTML或只是普通文本,innerHTML的時候爲true,textContent的時候爲false*/
    this.raw = false
    /*靜態節點標誌*/
    this.isStatic = false
    /*是否作爲跟節點插入*/
    this.isRootInsert = true
    /*是否爲註釋節點*/
    this.isComment = false
    /*是否爲克隆節點*/
    this.isCloned = false
    /*是否有v-once指令*/
    this.isOnce = false
  }

  // DEPRECATED: alias for componentInstance for backwards compat.
  /* istanbul ignore next https://github.com/answershuto/learnVue*/
  get child (): Component | void {
    return this.componentInstance
  }
}

這是一個最基礎的VNode節點,作爲其他派生VNode類的基類,裏面定義了下面這些數據。

tag: 當前節點的標籤名

data: 當前節點對應的對象,包含了具體的一些數據信息,是一個VNodeData類型,可以參考VNodeData類型中的數據信息

children: 當前節點的子節點,是一個數組

text: 當前節點的文本

elm: 當前虛擬節點對應的真實dom節點

ns: 當前節點的名字空間

context: 當前節點的編譯作用域

functionalContext: 函數化組件作用域

key: 節點的key屬性,被當作節點的標誌,用以優化

componentOptions: 組件的option選項

componentInstance: 當前節點對應的組件的實例

parent: 當前節點的父節點

raw: 簡而言之就是是否爲原生HTML或只是普通文本,innerHTML的時候爲true,textContent的時候爲false

isStatic: 是否爲靜態節點

isRootInsert: 是否作爲跟節點插入

isComment: 是否爲註釋節點

isCloned: 是否爲克隆節點

isOnce: 是否有v-once指令


打個比方,比如說我現在有這麼一個VNode樹

{
    tag: 'div'
    data: {
        class: 'test'
    },
    children: [
        {
            tag: 'span',
            data: {
                class: 'demo'
            }
            text: 'hello,VNode'
        }
    ]
}

渲染之後的結果就是這樣的

<div class="test">
    <span class="demo">hello,VNode</span>
</div>

生成一個新的VNode的方法

下面這些方法都是一些常用的構造VNode的方法。

createEmptyVNode 創建一個空VNode節點

/*創建一個空VNode節點*/
export const createEmptyVNode = () => {
  const node = new VNode()
  node.text = ''
  node.isComment = true
  return node
}

createTextVNode 創建一個文本節點

/*創建一個文本節點*/
export function createTextVNode (val: string | number) {
  return new VNode(undefined, undefined, undefined, String(val))
}

createComponent 創建一個組件節點

 // plain options object: turn it into a constructor https://github.com/answershuto/learnVue
  if (isObject(Ctor)) {
    Ctor = baseCtor.extend(Ctor)
  }

  // if at this stage it's not a constructor or an async component factory,
  // reject.
  /*Github:https://github.com/answershuto*/
  /*如果在該階段Ctor依然不是一個構造函數或者是一個異步組件工廠則直接返回*/
  if (typeof Ctor !== 'function') {
    if (process.env.NODE_ENV !== 'production') {
      warn(`Invalid Component definition: ${String(Ctor)}`, context)
    }
    return
  }

  // async component
  /*處理異步組件*/
  if (isUndef(Ctor.cid)) {
    Ctor = resolveAsyncComponent(Ctor, baseCtor, context)
    if (Ctor === undefined) {
      // return nothing if this is indeed an async component
      // wait for the callback to trigger parent update.
      /*如果這是一個異步組件則會不會返回任何東西(undifiened),直接return掉,等待回調函數去觸發父組件更新。s*/
      return
    }
  }

  // resolve constructor options in case global mixins are applied after
  // component constructor creation
  resolveConstructorOptions(Ctor)

  data = data || {}

  // transform component v-model data into props & events
  if (isDef(data.model)) {
    transformModel(Ctor.options, data)
  }

  // extract props
  const propsData = extractPropsFromVNodeData(data, Ctor, tag)

  // functional component
  if (isTrue(Ctor.options.functional)) {
    return createFunctionalComponent(Ctor, propsData, data, context, children)
  }

  // extract listeners, since these needs to be treated as
  // child component listeners instead of DOM listeners
  const listeners = data.on
  // replace with listeners with .native modifier
  data.on = data.nativeOn

  if (isTrue(Ctor.options.abstract)) {
    // abstract components do not keep anything
    // other than props & listeners
    data = {}
  }

  // merge component management hooks onto the placeholder node
  mergeHooks(data)

  // return a placeholder vnode
  const name = Ctor.options.name || tag
  const vnode = new VNode(
    `vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
    data, undefined, undefined, undefined, context,
    { Ctor, propsData, listeners, tag, children }
  )
  return vnode
}

cloneVNode 克隆一個VNode節點

export function cloneVNode (vnode: VNode): VNode {
  const cloned = new VNode(
    vnode.tag,
    vnode.data,
    vnode.children,
    vnode.text,
    vnode.elm,
    vnode.context,
    vnode.componentOptions
  )
  cloned.ns = vnode.ns
  cloned.isStatic = vnode.isStatic
  cloned.key = vnode.key
  cloned.isCloned = true
  return cloned
}

createElement

// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode {
  /*兼容不傳data的情況*/
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  /*如果alwaysNormalize爲true,則normalizationType標記爲ALWAYS_NORMALIZE*/
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  /*Github:https://github.com/answershuto*/
  /*創建虛擬節點*/
  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 {
  /*
    如果data未定義(undefined或者null)或者是data的__ob__已經定義(代表已經被observed,上面綁定了Oberver對象),
    https://cn.vuejs.org/v2/guide/render-function.html#約束
    那麼創建一個空節點
  */
  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()
  }
  /*如果tag不存在也是創建一個空節點*/
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // support single function children as default scoped slot
  /*默認默認作用域插槽*/
  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
  if (typeof tag === 'string') {
    let Ctor
    /*獲取tag的名字空間*/
    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
      /*從vm實例的option的components中尋找該tag,存在則就是一個組件,創建相應節點,Ctor爲組件的構造類*/
      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
    /*tag不是字符串的時候則是組件的構造類*/
    vnode = createComponent(tag, data, context, children)
  }
  if (isDef(vnode)) {
    /*如果有名字空間,則遞歸所有子節點應用該名字空間*/
    if (ns) applyNS(vnode, ns)
    return vnode
  } else {
    /*如果vnode沒有成功創建則創建空節點*/
    return createEmptyVNode()
  }
}

createElement用來創建一個虛擬節點。當data上已經綁定__ob__的時候,代表該對象已經被Oberver過了,所以創建一個空節點。tag不存在的時候同樣創建一個空節點。當tag不是一個String類型的時候代表tag是一個組件的構造類,直接用new VNode創建。當tag是String類型的時候,如果是保留標籤,則用new VNode創建一個VNode實例,如果在vm的option的components找得到該tag,代表這是一個組件,否則統一用new VNode創建。

關於

作者:染陌

Email:[email protected] or [email protected]

Github: https://github.com/answershuto

Blog:http://answershuto.github.io/

知乎專欄:https://zhuanlan.zhihu.com/ranmo

掘金: https://juejin.im/user/58f87ae844d9040069ca7507

osChina:https://my.oschina.net/u/3161824/blog

轉載請註明出處,謝謝。

歡迎關注我的公衆號

img

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章