Vue.js--Virtual Dom概述、VNode类型与属性详解

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/cold___play/article/details/102686625

Virtual Dom

Virtual Dom并不是真正意义上的DOM,而是一个轻量级的JavaScript对象,在状态发生变化时,Virtual Dom会进行Diff运算,来更新只需要被替换的DOM,而不是全部重绘。

与DOM操作相比,Virtual Dom是基于JavaScript计算的,所以开销会小很多。

Virtual Dom运行过程:
在这里插入图片描述
示例:
正常的DOM节点在HTML中是这样的:

<div id="main">
    <p>文本内容</p>
    <p>文本内容</p>
</div>

用Virtual Dom创建的JavaScript对象一般会是这样的:

var vNode = {
    tag: 'div',
    attributes:{
        id: 'main'
    },
    children: {
        //p节点
    }
}

VNode

在Vue.js 2 中,Virtual Dom 就是通过一种VNode类表达的,每个DOM元素或组件都对应一个VNode对象,在Vue.js 源码中是这样定义的:

export interface VNode{
    tag?: string;
    data?: VNodeData;
    children?: VNode[];
    text?: string;
    elm?: Node;
    ns?: string;
    context?: Vue;
    key?: string | number;
    componentOptions?: VNodeComponentOptions;
    componentInstance?: Vue;
    parent?: VNode;
    raw?: boolean;
    isStatic?: boolean;
    isRootInsert: boolean;
    isComment: boolean;
}  

VNodeData代码如下:

export interface VNodeData{
    key?: string | number;
    slot?: string;
    scopedSlots?: {[key: string]: ScopedSlot};
    ref?: string;
    tag?: string;
    staticClass?: string;
    class?: any;
    staticStyle?: {[key: string]: any};
    style?: {[key: string]: any};
    props?: {[key: string]: any};
    attrs?: {[key: string]: any};
    domProps?: {[key: string]: any};
    hook?: {[key: string]: Function};
    on?: {[key: string]: Function | Function[]};
    transition?: Object;
    show?: boolean;
    inlineTemplate?: {
        render: Function;
        staticRenderFns: Function[];
    };
    directives?: VNodeDirective[];
    keepAlive?: boolean;

}

具体含义如下:

  • children: 子节点,数组,也是VNode类型
  • text: 当前节点的文本,一般文本节点或注释节点会有该属性
  • elm: 当前虚拟节点对应的真实的DOM节点
  • ns: 节点的namespace
  • context: 编译作用域
  • functionlContext: 函数化组件的作用域
  • key: 节点的key属性,用于作为节点的标识,有利于patch的优化
  • componentOptions: 创建组件实例时会用到的选项信息
  • child: 当前节点对应的组件实例
  • parent: 组件的占位节点
  • raw: 原始html
  • isStatic: 静态节点的标识
  • isRootInsert: 是否作为根节点插入,被<transition>包裹的节点,概述性的值为false
  • isComment: 当前节点是否是注释节点
  • isCloned: 当前节点是否为克隆节点
  • isOnce: 当前节点是否有v-once指令

VNode类型

  • TextVNode: 文本节点
  • ElementVNode: 普通元素节点
  • ComponentVNode: 组件节点
  • EmptyVNode: 没有内容的注释节点
  • CloneVNode: 克隆节点,可以是以上任意类型的节点,唯一的区别在于isCloned属性为true

猜你喜欢

转载自blog.csdn.net/cold___play/article/details/102686625
今日推荐