VirtualDom: intro
https://ubugeeei.github.io/chibivue/10-minimum-example/040-minimum-virtual-dom.html#virtual-dom%E3%80%81何に使われる
前回までのコードの問題点
code: packages/runtime-core/renderer.ts
const render: RootRenderFunction = (vnode, container) => {
while (container.firstChild) container.removeChild(container.firstChild) // <- renderが走るたびに一度全てのDOMを削除し、再生成している
const el = renderVNode(vnode)
hostInsert(el, container)
}
リアクティビティな値に更新があるたびに、一度全ての DOM を削除し、1 から再生成している。
これは無駄が多いので、差分があったところのみ更新するようにしたい!
今回の目標
code: ts
// 元のVDOM
const vnode = {
type: "div",
props: { id: "my-app" },
children: [
{
type: "p",
props: {},
children: [count: 0]
},
{
type: "button",
{ onClick: increment },
children: "increment"
}
]
}
// 更新後のVDOM
const nextVnode = {
type: "div",
props: { id: "my-app" },
children: [
{
type: "p",
props: {},
children: [count: 1] // ここの値が変更された!
},
{
type: "button",
{ onClick: increment },
children: "increment"
}
]
}
元の VDOM と更新後の VDOM を比較して、差分だけレンダリングするようにしたい!
code: ts
const vnode = {...}
const nextVnode = {...}
patch(vnode, nextVnode, container)
この差分レンダリングする関数のことを「パッチ関数」と呼ぶ