Table of contents
Because directly operating the real DOM will affect efficiency. So vue uses virtual DOM (VNode) to describe the content to be rendered.
Virtual DOM
It is a js object, such as:
const vnode = {
tag: "h1",
children: [
{
tag: undefined, text: "Hello World"}
]
}
In addition, vue's template is not a real DOM, it will be compiled into a rendering function render
: a function used to return a virtual DOM tree .
<div id="app">
<h1>第一个vue应用:{
{title}}</h1>
<p>描述:{
{author}}</p>
</div>
render
Function execution will return a structure similar to the following (virtual DOM tree) and create actual DOM nodes based on it.
{
tag: "div",
children: [
{
tag: "h1", children: [ {
text: "第一个vue应用:Hello World" } ] },
{
tag: "p", children: [ {
text: "描述:desc" } ] }
]
}
When dependent data changes, re-rendering will be triggered. vue will compare the old and new VNode trees and find the differences, and only apply the differences (necessary updates) to the real DOM tree.
Therefore, to get the final page in vue, a virtual DOM tree must be generated first . The logic is as follows:
Virtual DOM tree generation process
vue official website reference
1. If there is render
a function, run it.
2. Otherwise, determine whether there is template
an attribute, and if so, template
use the configuration as a template and compile it into render
a function to run.
3. Otherwise, use el
the bound DOM element as a template and compile it into render
a function to run.
The following 3 examples have the same rendering results.
Example 1, only render
function
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
const vm = new Vue({
el: "#app",
data: {
title: "你好 vue",
desc: "第一个 vue 应用",
},
render(h) {
return h("div", [
h("h1", this.title),
h("p", `描述:${
this.desc}`),
]);
},
});
</script>
</body>
Example 2, only template
attributes
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
const vm = new Vue({
el: "#app",
data: {
title: "你好 vue",
desc: "第一个 vue 应用",
},
template: `<div>
<h1>{
{title}}</h1>
<p>描述:{
{desc}}</p>
</div>`,
});
</script>
</body>
Example 3, use el
the corresponding outerHTML
as a template
<body>
<div id="app">
<div>
<h1>{
{title}}</h1>
<p>描述:{
{desc}}</p>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
const vm = new Vue({
el: "#app",
data: {
title: "你好 vue",
desc: "第一个 vue 应用",
},
});
</script>
</body>
that's all.