美文网首页
虚拟DOM(1)

虚拟DOM(1)

作者: _William_Zhang | 来源:发表于2018-09-29 22:03 被阅读3次

代码如下:

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()

相关文章

网友评论

      本文标题:虚拟DOM(1)

      本文链接:https://www.haomeiwen.com/subject/mfxioftx.html