組合模式
// @returns {VNode}
createElement(
// {String | Object | Function}
// 一個 HTML 標簽名、組件選項對象,或者
// resolve 了上述任何一種的一個 async 函數(shù)。必填項。
'div',
// {Object}
// 一個與模板中 attribute 對應的數(shù)據(jù)對象??蛇x。
{
// (詳情見下一節(jié))
},
// {String | Array}
// 子級虛擬節(jié)點 (VNodes),由 `createElement()` 構建而成,
// 也可以使用字符串來生成“文本虛擬節(jié)點”。可選。
[
'先寫一些文字',
createElement('h1', '一則頭條'),
createElement(MyComponent, {
props: {
someProp: 'foobar'
}
})
]
)
function createElement(tag, attr, children) {
const element = document.createElement(tag)
if (typeof children === undefined) {
children = attr
} else {
for (let i in attr) {
element.setAttribute(i, attr[i])
}
}
if (typeof children === 'string') {
const textNode = document.createTextNode(children)
element.appendChild(textNode)
} else {
children.forEach(item => {
if (typeof item === 'string') {
item = document.createTextNode(item)
}
element.appendChild(item)
})
}
return element
}
const body = document.querySelector('body')
body.appendChild(createElement(
'div',
{ class: 'box' },
[
'hello universe',
createElement('a', { href: 'www.baidu.com' }, '百度')
]
)
)