Szybka pomoc

Ściągawka z Virtual-DOM

Skrócony przewodnik po virtual-dom: węzły hyperscript, createElement, algorytm diff oraz operacje patch.

· Opublikowano

virtual-dom to model DOM w JavaScript obsługujący wydajne renderowanie deklaratywne za pomocą operacji diff i patch.

Konfiguracja i importowanie modułów

const h = require('virtual-dom/h');
const diff = require('virtual-dom/diff');
const patch = require('virtual-dom/patch');
const createElement = require('virtual-dom/create-element');

Wstępne renderowanie i tworzenie elementów DOM

// 1: Create a virtual tree using hyperscript
const tree = h('div', { style: { color: 'blue' } }, ['Hello World']);

// 2: Create a real DOM element node from the virtual tree
const rootNode = createElement(tree);

// 3: Append to document body
document.body.appendChild(rootNode);

Kalkulacja różnic i aktualizacja (Diff & Patch)

// 4: Create a second updated virtual tree
const newTree = h('div', { style: { color: 'red' } }, ['Hello Updated World']);

// 5: Calculate the diff delta between old and new trees
const patches = diff(tree, newTree);

// 6: Patch the real DOM node in-place
patch(rootNode, patches);

Powiązane ściągawki

Powiązane tematy