什么是虚拟DOM?如何实现一个虚拟DOM?说说你的思路
参考答案
思路
核心三件事:用对象描述结构 → 把对象渲染成真实 DOM → 更新时 diff 新旧对象。
// 1) 创建 vnode
function h(tag, props = {}, children = []) {
return { tag, props, children, el: null }
}
// 2) 首次渲染:vnode → 真实 DOM
function mount(vnode, container) {
const el = document.createElement(vnode.tag)
vnode.el = el
// 属性
for (const [k, v] of Object.entries(vnode.props || {})) {
if (k.startsWith('on')) el.addEventListener(k.slice(2).toLowerCase(), v)
else el.setAttribute(k, v)
}
// 子节点:文本 or 数组
if (typeof vnode.children === 'string') el.textContent = vnode.children
else vnode.children.forEach(child => mount(child, el))
container.appendChild(el)
}
// 3) 更新:diff
function patch(n1, n2) {
// 类型不同 → 直接替换
if (n1.tag !== n2.tag) {
const el = n1.el
el.parentNode.replaceChild((() => {
const tmp = document.createElement('div')
mount(n2, tmp)
return tmp.firstElementChild
})(), el)
n2.el = n1.el.parentNode.lastChild
return
}
const el = (n2.el = n1.el)
// props diff
const o = n1.props || {}, p = n2.props || {}
for (const k in p) if (o[k] !== p[k]) setProp(el, k, p[k], o[k])
for (const k in o) if (!(k in p)) removeProp(el, k)
// children diff
diffChildren(el, n1, n2)
}
children 的最小 diff(keyed)
function diffChildren(parent, n1, n2) {
const oldCh = n1.children, newCh = n2.children
if (typeof newCh === 'string' && typeof oldCh === 'string') {
if (newCh !== oldCh) parent.textContent = newCh
return
}
// 简单版:按 key 建 map,逐个挂载/移动,最后删除多余
const oldMap = new Map()
oldCh.forEach((c, i) => c.key != null && oldMap.set(c.key, { c, i }))
let i = 0
newCh.forEach(nc => {
const hit = nc.key != null ? oldMap.get(nc.key) : null
if (hit) { patch(hit.c, nc); oldMap.delete(nc.key) }
else mount(nc, parent) // 新增
// 移动:按位置 appendChild(或用 insertBefore 精确位置)
parent.appendChild(nc.el)
})
oldMap.forEach(({ c }) => parent.removeChild(c.el)) // 删除
}
真实框架比这多的部分
- 双端/LIS 优化(Vue)或 Fiber 调度(React),减少移动次数;
- 组件 vnode:需要实例化、props 更新、插槽;
- 事件与属性差异:
class/style特殊处理、受控属性(value/checked)、ref; - Fragment / Teleport / Suspense / 异步组件;
- 静态标记与 patchFlag(Vue 3)避免无谓比较;
- SSR 与 hydration:把服务端 HTML 与 vnode 对应起来;
- 跨平台 renderer:把
document.createElement抽成nodeOps。
回答时的结构
先讲「三件套」(vnode 结构、mount、patch + keyed children diff),再说「真实框架额外做了什么」,最后点出复杂度:朴素 O(n²),keyed map 版 O(n),Vue 3 因编译标记进一步下降。