<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>使用配置项抽离封装API</title>
</head>
<body>
<div id="app"></div>
<script>
/**
* 自定义渲染器
*/
function createRenderer(options) {
const {
createElement,
insert,
setElementText
} = options
function render(vnode, container) {
if (vnode) {
patch(container._vnode, vnode, container);
} else {
container.innerHTML = "";
}
container._vnode = vnode;
}
function patch(n1, n2, container) {
// console.log('container', container);
if (!n1) {
mountElement(n2, container);
} else {
// 打补丁
}
}
// 主要改动这里
function mountElement(vnode, container) {
const el = createElement(vnode.type);
if (typeof vnode.children === "string") {
setElementText(el, vnode.children)
}
insert(el, container)
}
return { render };
}
// 测试代码
const renderer = createRenderer({
createElement(tag) {
return document.createElement(tag)
},
setElementText(el, text) {
el.textContent = text
},
insert(el, parent, anchor = null) {
parent.insertBefore(el, anchor)
}
});
const vnode = {
type: "h1",
children: "hello world",
};
renderer.render(vnode, document.querySelector("#app"));
</script>
</body>
</html>