简析
- vdom是由js对象节点组成的一个树状结构,通过diff算法对比js对象节点来更新,最后映射到原生的dom中
- 一个简单的dom结构
<div id="container">
<h1 style="color: red">vdom与html相互转换</h1>
<p>hello vdom and html</p>
<ul>
<li>item #1</li>
<li>item #2</li>
</ul>
</div>
class VNode {
constructor(tagName, props, children) {
this.tagName = tagName
this.props = props
this.children = children
}
}
var vNode1 = new VNode('div', { 'id': 'container' }, [
new VNode('h1', { style: 'color:red' }, ['vdom与html相互转换']),
new VNode('p', {}, ['hello vdom and html']),
new VNode('ul', {}, [new VNode('li', {}, ['item #1']), new VNode('li', {}, ['item #2'])]),
])
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vdom与Html的相互转化</title>
</head>
<body>
<script src="vNode.js"></script>
</body>
</html>
var setAttr = function (node, key, value) {
switch (key) {
case 'style':
node.style.cssText = value
break
case 'value':
var tagName = node.tagName || ''
tagName = tagName.toLowerCase()
if (tagName === 'input' || tagName === 'textarea') {
node.value = value
} else {
node.setAttribute(key, value)
}
break
default:
node.setAttribute(key, value)
break
}
}
class VNode {
constructor(tagName, props, children) {
this.tagName = tagName
this.props = props
this.children = children
}
render() {
var el = document.createElement(this.tagName)
var props = this.props
for (var propName in props) {
setAttr(el, propName, props[propName])
}
this.children.forEach(child => {
var childNode = (child instanceof VNode) ? child.render() : document.createTextNode(child)
el.appendChild(childNode)
})
return el
}
}
var vNode1 = new VNode('div', { 'id': 'container' }, [
new VNode('h1', { style: 'color:red' }, ['vdom与html相互转换']),
new VNode('p', {}, ['hello vdom and html']),
new VNode('ul', {}, [new VNode('li', {}, ['item #1']), new VNode('li', {}, ['item #2'])]),
])
var rootNode = vNode1.render()
document.body.appendChild(rootNode)
Github