vdom到实际到真实dom的简易实现
<!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>
<div id="app"></div>
<script src="./1.js"></script>
<script>
function h(a, b, c) {
return {
a,
b,
c,
};
}
const vonode1 = h("div", { class: "sy" }, [
h(
"button",
{
onclick: function () {
alert("点击");
},
},
"点击按钮"
),
h("div", null, "div标签"),
]);
function mount(vonode, container) {
const el = (vonode.el = document.createElement(vonode.a));
console.log(el);
if (vonode.b) {
console.log(vonode.b);
for (const key in vonode.b) {
const value = vonode.b[key];
if (key.startsWith("on")) {
console.log(key.slice(2).toLowerCase());
el.addEventListener(key.slice(2).toLowerCase(), value);
} else {
el.setAttribute(key, value);
}
}
}
if (vonode.c) {
if (typeof vonode.c === "string") {
el.textContent = vonode.c;
} else {
vonode.c.forEach((element) => {
mount(element, el);
});
}
}
container.appendChild(el);
}
mount(vonode1, document.querySelector("#app"));
</script>
</body>
</html>