class Element {
constructor (type, props, children) {
this.type = type
this.props = props
this.children = children
}
}
const ul = createElement(
'ul',
{id: 'list'},
[
createElement('li', {class: 'item'}, ['Item 1']),
createElement('li', {class: 'item'}, ['Item 2']),
createElement('li', {class: 'item'}, ['Item 3'])
]
)
function createElement (type, props, children) {
return new Element(type, props, children)
}
function createNode (node) {
let el = document.createElement(node.type)
for (let key in node.props) {
if (node.type.toUpperCase() === 'INPUT' || node.type.toUpperCase() === 'TEXTAREA') {
el.value = node.props[key]
} else {
el.setAttribute(key, node.props[key])
}
}
return el
}
ul.render = function (node = ul) {
let root = createNode(node)
if (node.children && node.children.length > 0) {
node.children.forEach(ele => {
if (ele instanceof Element) {
root.appendChild(ul.render(ele))
} else {
root.appendChild(document.createTextNode(ele))
}
})
}
return root
}
const ulRoot = ul.render()
document.body.appendChild(ulRoot)
阅读vue源码后,简单实现虚拟dom
最新推荐文章于 2024-04-29 15:10:57 发布