<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 一些项目比较大的话,操作真实dom就可能会繁琐一点点,可能也会卡顿 -->
<!-- 虚拟dom本质其实就是一个js对象 -->
<!-- 平时我们一些普通的dom结构举例如下 -->
<!-- <div class="box">
<span>123</span>
--678
</div> -->
<!-- 而虚拟对象则通过一个js对象来进行展示 -->
<!-- 普通的dom结构 其中的属性非常非常的多,有很多都用不到,所以说操作它可能会繁琐一些 -->
<script>
// 虚拟Dom
const vDom = {
type: 'div',
props: {
id: "box",
className: 'box1'
},
children: [
{
type: 'span',
props: {},
children:['123']
},
'--678'
]
}
// 将虚拟Dom 转换为真实 Dom
function vDomTorDom({ type, props, children }) {
// 1、根据type创建标签
const rDom = document.createElement(type)
// 2、给当前真实dom添加属性
Object.keys(props).forEach(item => {
rDom[item] = props[item]
})
// 3、添加子元素
children.forEach(item => {
if (typeof item === "string") {
const text = document.createTextNode(item)
rDom.appendChild(text)
} else {
rDom.appendChild(vDomTorDom(item))
}
})
return rDom
}
// 将虚拟dom添加到页面中
document.body.appendChild(vDomTorDom(vDom))
</script>
</body>
</html>