当前位置:网站首页>Implementation principle of virtual DOM
Implementation principle of virtual DOM
2022-07-25 03:05:00 【Aviator_ huahua】
Virtual DOM Implementation principle of
summary
What is? Virtual DOM
- Virtual DOM( fictitious DOM), It's ordinary JS Object to describe DOM object
Why use Virtual DOM
- MVVM The framework solves the problem of view and state synchronization
- Template engine can simplify view operation , But there is no way to track the status
- fictitious DOM You can maintain the status of the program , Track the last status , Update the real status by comparing the difference between the two previous status DOM
fictitious DOM The role of
- Maintain the relationship between view and state
- Improve rendering performance in complex views
- Cross platform
- Browser platform rendering DOM
- Server rendering SSR(Nuxt.js/Next.js)
- Native applications (Weex/React Native)
- Applet (mpvue/uni-app) etc.
Snabbdom
install
Create project directory
md snabbdom-demoEnter project directory
cd snabbdom-demoestablish package.json
npm init -yLocal installation parcel
npm install parcel-bundler -D npm install [email protected]
To configure
package.json
"scripts": {
"dev": "parcel index.html --open",
"build": "parcel build index.html"
}
Create directory structure
│ index.html
│ test.md
│
└─src
basicusage.js
Basic use
import {
init
} from 'snabbdom/build/package/init'
import {
h
} from 'snabbdom/build/package/h'
let patch = init([])
let vnode = h('div#container', [
h('h1', 'Hello Snabbdom'),
h('p', ' This is a p'),
])
let app = document.querySelector('#app')
let oldVNode = patch(app, vnode)
setTimeout(() => {
// vnode = h('div#container', [
// h('h1', 'Hello world'),
// h('p', 'Hello p'),
// ])
// patch(oldVNode, vnode)
// eliminate div The content in h(!) Generate an empty comment node
patch(oldVNode, h('!'))
}, 2000)
npm run dev function
modular
Module function
- Snabbdom The core library does not handle DOM Attribute of element / style / Events, etc. , You can register Snabbdom It is implemented by the module provided by default
- Snabbdom Modules in can be used to extend Snabbdom The function of
- Snabbdom The module in is implemented by registering the global hook function
Official module
attributes
Set up VNode Corresponding DOM Element attributes , For internal use setAttribute Realization . Would be right DOM Element boolean type attributes ,selected、checked etc.
props
Set attributes in the way of object point attributes , Do not handle Boolean attributes
dataset
Handle H5 Medium
data-attributeclass
Switch class styles
style
Set inline style
eventlisteners
Register remove event
How to use the module
- Import the required modules
- init() Registration module in
- h() The module... Is used at the second argument of the function
import {
init
} from 'snabbdom/build/package/init'
import {
h
} from 'snabbdom/build/package/h'
// 1、 The import module
import {
styleModule
} from 'snabbdom/build/package/modules/style'
import {
eventListenersModule
} from 'snabbdom/build/package/modules/eventlisteners'
// 2、 Registration module
const patch = init([
styleModule,
eventListenersModule
])
// 3、 Use h() The second parameter of the function , Data used in the incoming module ( object )
let vnode = h('div', [
h('h1', {
style: {
backgroundColor: 'red'
}
},
'Hello world'
),
h('p', {
on: {
click: eventHandler
}
}, 'Hello P'),
])
function eventHandler() {
console.log(' Stop it ');
}
let app = document.querySelector('#app')
let oldNode = patch(app, vnode)
Source code
How to learn the source code
- Macro understanding
- Look at the source code with the target , natural
- debugging
- Reference material
Snabbdom At the heart of
- init() Set up modules , establish patch() function
- Use h() Function creation JavaScript object (VNode) Describe reality DOM
- patch() Compare the old and new VNode
- Update the changed content to the real DOM Trees
h function
effect
establish VNode object
function overloading
- Functions with different parameter numbers or parameter types
- JavaScript There is no concept of overloading in
- TypeScript There are heavy loads in , However, the implementation of overloading still adjusts parameters through code
VNode
Use JavaScript Object description DOM node
The basic structure
// vnode.ts
export declare type Key = string | number; // Unique identification
// Definition VNode Object required properties
export interface VNode {
sel: string | undefined; // Selectors
data: VNodeData | undefined; // Describe the data required in the module
children: Array<VNode | string> | undefined; // Child node
elm: Node | undefined; // At present VNode Object into DOM Elements
text: string | undefined; // Text node content
key: Key | undefined; // Unique identification
}
// constraint VNode in data Type of attribute
export interface VNodeData {
props?: Props;
attrs?: Attrs;
class?: Classes;
style?: VNodeStyle;
dataset?: Dataset;
on?: On;
hero?: Hero;
attachData?: AttachData;
hook?: Hooks;
key?: Key;
ns?: string;
fn?: () => VNode;
args?: any[];
[key: string]: any;
}
export function vnode (sel: string | undefined,
data: any | undefined,
children: Array<VNode | string> | undefined,
text: string | undefined,
elm: Element | Text | undefined): VNode {
const key = data === undefined ? undefined : data.key
return { sel, data, children, text, elm, key }
}
patch Overall process analysis
- patch(oldVNode,newVNode)
- Render the changed content in the new node to the real DOM, Finally, the new node is returned as the old node for the next processing
- Contrast the old with the new VNode Whether the same node ( Node key and sel identical )
- If it's not the same node , Delete the previous content , To render
- If it is the same node , Then judge the new VNode Is there a text, If there is and with oldVNode Of text Different , Update the text directly
- If the new VNode Yes children, Determine whether there are changes in the child nodes
init
Cache parameters , return patch function
边栏推荐
- Class notes (4) (2) -- 572. Compete
- Operator explanation - C language
- Win10 -- open the hosts file as an administrator
- Use of stm32cubemonitor part I - data plotting and instrument display
- Daily three questions 7.19
- Learning Record V
- Domestic edge computing organization and product research
- How to switch terminators in PostgreSQL?
- JS foundation -- regular expression
- JS written test questions -- random numbers, array de duplication
猜你喜欢

Wechat sports field reservation of the finished works of the applet graduation project (5) assignment

Decoding webp static pictures using libwebp

Classic network learning RESNET code implementation

DOM operation -- get elements and nodes

Selenium framework operation steelth.min.js file hides browser fingerprint features

Use unicloud cloud function to decode wechat motion steps in applet

JS construct binary tree

Learning record Xi

Wechat sports field reservation of applet completion works applet graduation design (8) graduation design thesis template

JS written test question -- deep copy of object
随机推荐
Canvas record
Use reflection to convert RDD to dataframe
Banana pie bpi-m5 toss record (2) -- compile u-boot
JS written test questions -- random numbers, array de duplication
Jenkins plug-in development -- plug-in expansion
Operator explanation - C language
Brief understanding of operational amplifier
JS written test question -- promise, setTimeout, task queue comprehensive question
Download the jar package of jsqlparser and PageHelper
JS written test -- regular expression
C: wechat chat software instance (wpf+websocket+webapi+entityframework)
Vulntarget vulnerability shooting range -vulntarget-b
Dynamic planning of force buckle punch in summary
Execution methods with static code blocks and child and parent classes
[stm32f130rct6] idea and code of ultrasonic ranging module
[stm32f103rct6] motor PWM drive module idea and code
How to use blender to make 360 degree panorama and panoramic video?
Color space (2) -- YUV
Use of stm32cubemonitor Part II - historical data storage and network access
Error: tomee required to support ear/ejb deployment