VNode简介

VNode说明&作用

VNode是什么

VNode是JavaScript对象。VNode表示Virtual DOM,用JavaScript对象来描述真实的DOMDOM标签,属性,内容都变成对象的属性。就像使用JavaScript对象对一种动物进行说明一样{name: 'Hello Kitty', age: 1, children: null}

VNode的作用

通过rendertemplate模版描述成VNode,然后进行一系列操作之后形成真实的DOM进行挂载。

VNode的优点
  1. 兼容性强,不受执行环境的影响。VNode因为是JS对象,不管Node还是浏览器,都可以统一操作,从而获得了服务端渲染、原生渲染、手写渲染函数等能力。
  2. 减少操作DOM,任何页面的变化,都只使用VNode进行操作对比,只需要在最后一步挂载更新DOM,不需要频繁操作DOM,从而提高页面性能。

VNode如何生成

Vue源码中,VNode是通过一个构造函数生成的。

export default class VNode {
  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions,
    asyncFactory?: Function
  ) {
    this.tag = tag
    this.data = data
    this.children = children
    this.text = text
    this.elm = elm
    this.ns = undefined
    this.context = context
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    this.key = data && data.key
    this.componentOptions = componentOptions
    this.componentInstance = undefined
    this.parent = undefined
    this.raw = false
    this.isStatic = false
    this.isRootInsert = true
    this.isComment = false
    this.isCloned = false
    this.isOnce = false
    this.asyncFactory = asyncFactory
    this.asyncMeta = undefined
    this.isAsyncPlaceholder = false
  }
}

VNode构造函数看起来十分简单,先走一遍VNode的生成过程。

// 模版
<a class="demo" style="color: red" href="#">
    generator VNode
</a>
// VNode描述
{
  tag: 'a',
  data: {
    calss: 'demo',
    attrs: {
      href: '#'
    },
    style: {
      color: 'red'
    }
  },
  children: ['generator VNode']
}

这个JS对象,已经囊括了整个模板的所有信息,完全可以根据这个对象来构造真实DOM

VNode存放哪些信息

  1. data:存储节点的属性,绑定的事件等
  2. elm:真实DOM 节点
  3. context:渲染这个模板的上下文对象
  4. isStatic:是否是静态节点

VNode存放

在初始化完选项,解析完模板之后,就需要挂载DOM了。此时就需要生成VNode,才能根据 VNode生成DOM然后挂载。创建出来的VNode需要被存起来,主要存放在三个位置:parent_vnode$vnode

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