What is a VNode

As we know, the Render function is converted to a VNode node. Virtual DOM is basically a tree based on JavaScript objects (vNodes), which are described by object attributes. In fact, it is just a layer of abstraction from the real DOM. Eventually, the tree can be mapped to the real world through a series of operations. Because Virtual DOM is based on JavaScript objects and does not depend on the real platform environment, it has the ability to cross platform, such as browser platform, Weex, Node, etc.

Implement a VNode

A VNode is essentially a JavaScript object, as long as the properties of the class correctly and intuitively describe the current node. Let’s implement a simple VNode class with some basic properties, but for the sake of understanding, let’s leave out the complications.

Class VNode {constructor (tag, data, children, text, elm) {/* This. Tag = tag; /* Props, attrs */ this. Data = data; /* The child of the current node is an array */ this.children = children; /* The text of the current node */ this.text = text; /* This. Elm = elm; }}Copy the code

For example, I currently have this Vue component.

<template>
  <span class="demo" v-show="isShow">
    This is a span.
  </span>
</template>

Copy the code

That’s what it looks like in JavaScript code.

Function render () {return new VNode(' SPAN ', {/* array of directives */ directives: [{/* V-show directives */ rawName: 'v-show', expression: 'isShow', name: 'show', value: true}], /* staticClass */ staticClass: 'demo' }, [ new VNode(undefined, undefined, undefined, 'This is a span.') ] ); }Copy the code

Take a look at the transition to VNode.

{tag: 'SPAN ', data: {/* Directives array */ directives: [{/* V-show directives */ rawName:' V-show ', expression: 'isShow', name: 'show', value: true}], /* staticClass */ staticClass: 'demo'}, text: undefined, children: [/* child is a text VNode */ {tag: undefined, data: undefined, text: 'This is a span.', children: undefined } ] }Copy the code

We can then wrap the VNode further and implement some methods for generating common VNodes.

  • Create an empty node
function createEmptyVNode () {
    const node = new VNode();
    node.text = '';
    return node;
}

Copy the code
  • Create a text node
function createTextVNode (val) {
  return new VNode(undefined, undefined, undefined, String(val));
}

Copy the code
  • Clone a VNode
function cloneVNode (node) {
    const cloneVnode = new VNode(
        node.tag,
        node.data,
        node.children,
        node.text,
        node.elm
    );
    return cloneVnode;
}

Copy the code

In general, VNode is a JavaScript object, which uses JavaScript object attributes to describe some states of the current node, and uses the form of VNode nodes to simulate a Virtual DOM tree.