Frame Design Overview
Chapter 1 The Art of Weighing
Chapter 2 Core Elements of the Framework Design
Chapter 3 Design Ideas of VUe.js
Declarative UI: Vue.js 3 is a declarative UI framework
. There are two ways to describe UI declaratively:
1. Template description
2. JavaScript object description
const vnode = {
tag: 'div',
props: {
onclick: () => alert('gl')
},
children: 'click me'
}
- The way to describe the UI using JavaScript objects is the so-called virtual DOM
- The content to be rendered by a component is described by the render function
initial renderer
The role of the renderer is to render the virtual DOM into a real DOM
function renderer(vnode, continer) {
// 使用虚拟dom的属性创建节点
const el = document.createElement(vnode.tag);
// 遍历vnode属性,将节点的属性或方法添加到dom元素
for (const key in vnode.props) {
if (/^on/.test(key)) {
el.addEventListener(
key.substring(2).toLowerCase(),
vnode.props[key]
)
}
}
// 处理children
if (typeof vnode.children === 'string') {
el.appendChild(document.createTextNode(vnode.children))
} else if (Array.isArray(vnode.children)) {
vnode.children.array.forEach(child => {
renderer(child, el)
});
}
continer.appendChild(el)
}
The renderer function accepts two parameters:
- vnode: virtual DOM object
- container: a real DOM element
The nature of components
In addition to describing the real DOM, the virtual DOM can also describe components.
A component is an encapsulation of a group of DOM elements
const vnode = {
tag:MyConpnent
}
When describing components, the tag attribute is no longer a tag name, but a
component function. But at the same time, does the component have a time function? Of course not, components can also be expressed as objects.
How templates work
Whether it is handwritten virtual DOM or using templates, it is a declarative description of UI, and Vue supports both UI representations.
So how does the template work ----> the compiler
The role of the compiler is to compile the template into a rendering function
as follows
<div @click='handler'>
click me
</div>
To the compiler, a template is a string that it parses and generates a render function that does the same.
render() {
return h('div',{
onClick:handler},'click me')
}
A .vue file is a component.
<template>
<div @click='handler'>
click me
</div>
</template>
<script>
export default {
data() {
/*···*/},
methods:{
/*···*/},
}
</script>
The content in the template tag is the template content. The compiler will compile the template content into a rendering function and add it to the component object of the script tag block, so the code that finally runs in the browser is:
export default {
data() {
/*···*/},
methods:{
/*···*/},
render() {
return h('div',{
onClick:handler},'click me')
}
}
For a component, the content to be rendered is ultimately generated by the rendering function, and then the renderer renders the virtual DOM returned by the rendering function as the real DOM. This is how templates work, which is the process of vue rendering pages. .