代码如下:
html
<!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>v-doem-es6</title>
</head>
<body>
<div id="root">
<h1>hello</h1>
<p><span>jirengu</span></p>
</div>
</body>
<script src="./v-dom-es6.js"></script>
</html>
js
class VNode {
constructor(tag, children, text) {
this.tag = tag
this.children = children
this.text = text
}
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())
vNodes
vNodes
vNodes.render()
vNodes.render()
网友评论