是什么
根据真实DOM创建的映射的数据结构,
要区分出两个的不同, 就是diff算法
有什么用
如何实现
大概思路:
- 用JavaScript对象结构表示DOM树的结构;然后用这个树构建真正的DOM树,放到页面中;
- 状态变更时,重新构造一棵树,将新树和旧树进行比较,记录差异;
- 将2中的差异应用到1构建的真实DOM树上,更新视图。
代码实现
class VNode {
constructor(tag, children, text) {
this.tag = tag
this.text = text
this.children = children
}
render() {
if(this.tag === '#text') {
return document.createTextNode(this.text)
}
let el = document.createElement(this.tag)
this.children.forEach(vChild => {
el.appendChild(vChild.render())
})
return el
}
}
function v(tag, children, text) {
if(typeof children === 'string') {
text = children
children = []
}
return new VNode(tag, children, text)
}
let vNodes = v('div', [
v('p', [
v('span', [ v('#text', 'xiedaimala.com') ] )
]
),
v('span', [
v('#text', 'jirengu.com')
])
]
)
console.log(vNodes)
console.log(vNodes.render())
function patchElement(parent, newVNode, oldVNode, index = 0) {
if(!oldVNode) {
parent.appendChild(newVNode.render())
} else if(!newVNode) {
parent.removeChild(parent.childNodes[index])
} else if(newVNode.tag !== oldVNode.tag || newVNode.text !== oldVNode.text) {
parent.replaceChild(newVNode.render(), parent.childNodes[index])
} else {
for(let i = 0; i < newVNode.children.length || i < oldVNode.children.length; i++) {
patchElement(parent.childNodes[index], newVNode.children[i], oldVNode.children[i], i)
}
}
}
let vNodes1 = v('div', [
v('p', [
v('span', [ v('#text', 'xiedaimala.com') ] )
]
),
v('span', [
v('#text', 'jirengu.com')
])
]
)
let vNodes2 = v('div', [
v('p', [
v('span', [
v('#text', 'xiedaimala.com')
] )
]
),
v('span', [
v('#text', 'jirengu.coms'),
v('#text', 'ruoyu')
])
]
)
const root = document.querySelector('#root')
patchElement(root, vNodes1)