基本概念介绍:
虚拟DOM节点, vue源码中命名为vnode。
vnode是一个用来描述真实DOM节点的js对象,它与真实DOM节点一一对应,vue渲染视图时会根据vnode为模板进行渲染。
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的实例:
{
tag: 'div'
data: {
class: 'test'
},
children: [
{
tag: 'span',
data: {
class: 'demo'
}
text: 'hello,VNode'
}
]
}
渲染出来的真实DOM是这样的:
<div class="test">
<span class="demo">hello,VNode</span>
</div>
vnode中有三种节点:
1. 注释节点,也就是我们代码中的注释,标志是 vnode.isComment 为true。
2. 文本节点,例如<p>text</p>,p就是文本节点 标志是 vnode.text不为空。
3. 元素节点,不是以上两种情况的节点视为元素节点。
vnode的作用:
为什么vue2.0中要引入vnode这个概念?
vue在更新视图时会用原本的vnode与新生成的vnode做对比,找出它们的差异,做为补丁精准的更新真实DOM节点。
如果我们没有用vnode,每次依赖的变量发生变化时,整个视图都需要重新渲染,所以引入vnode是为了提高视图渲染的效果。
对vue的具体渲染过程感兴趣的小伙伴可以看这一篇文章:
解析vue2.x源码 diff算法 (https://blog.csdn.net/qq_36259513/article/details/103152653)