To write HTML structure through VUE, tempplate attribute is generally recommended, which is easy to use. The specific code is as follows:
Example 1: use template to render ul list
var vm = new Vue({
el:"#demo1",
template:`
<ul class = "bg" style = "fontSize:20px" abc = "yyy">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
`
});
However, in some practical application scenarios, you really need the full programming ability of JavaScript, which is the render function, which is closer to the compiler than template. Example code is as follows:
Example 2: rendering ul list with render function
var vm = new Vue({
el:"#demo",
render(createElement){
var obj = createElement(
"ul",
{
class: {
bg:true
},
style:{
fontSize:"50px"
},
attrs:{
abc:"yyy"
},
},
[
createElement("li",1),
createElement("li",2),
createElement("li",3)
]
);
console.log( obj );
return obj;
}
});
Example 2 and example 1 are two ways to implement virtual DOM in VUE, and the final browser rendering effect is the same;
Next, let's learn about DOM tree and virtual DOM
The real DOM node tree of HTML is shown in the figure below
The process of building virtual DOM node tree of vue is shown in the figure below
Through this process, we can see that the render function uses createElement to return a virtual DOM, thus rendering the real dom. Then you can monitor and keep track of the changes in the virtual DOM through the watcher. The information it contains will tell the Vue what kind of nodes to render on the page and their children. Through this process, Vue will automatically keep the page updated, and the developer can update all DOM nodes efficiently,
The virtual dom of vue generates the data diagram of DOM
A brief introduction to render function
Next you need to be familiar with how to generate templates in the createElement function. Here are the parameters accepted by createElement:
createElement(
// 1. Pass in the root node you want to generate the outermost layer
// {String | Object | Function}
// It can be an HTML tag string, a component option object, or
// Parsing any of the above async asynchronous functions, the necessary parameters.
'ul',
// 2. A data object containing DOM node related attributes
// {Object}
// Set the properties in the generated DOM. General operation root node, optional parameters.
{
class: {
bg:true
},
style:{
fontSize:"50px"
},
attrs:{
abc:"yyy"
},
domProps:{
/*innerHTML:"<li>I am the html structure inside < / Li >“ */
}
},
// 3. Generate child nodes
// {String | Array}
// The child node is built by 'createElement()',
// You can also use strings to generate text nodes. Optional parameters.
[
createElement("li",1),
createElement("li",2),
createElement("li",3)
]
)