Skip to content

Instantly share code, notes, and snippets.

@dickenslian
Last active September 14, 2021 02:35
Show Gist options
  • Save dickenslian/86c4e266ae5f2134373376133bec9e3d to your computer and use it in GitHub Desktop.
Save dickenslian/86c4e266ae5f2134373376133bec9e3d to your computer and use it in GitHub Desktop.
你不知道对Virtual DOM(一)
<body>
<script src="compiled.js"></script>
<style>
body { margin: 0; font-size: 24; font-family: sans-serif }
.li-1 { background: red }
</style>
<main id="main"></main>
<script>
var main = document.getElementById('main')
render(main)
</script>
</body>
function flatten(arr) {
return [].concat.apply([], arr);
}
function h(tag, props, ...children) {
return {
tag,
props: props || {},
children: flatten(children) || []
};
}
function render(parent) {
const vdom = view();
const element = createElement(vdom);
parent.appendChild(element);
}
function view() {
return (
<div>
Hello World
<ul>
<li id="1" class="li-1">
第1
</li>
</ul>
</div>
);
}
// 创建dom元素
function createElement(vdom) {
// 如果vdom是字符串或者数字类型,则创建文本节点,比如“Hello World”
if (typeof vdom === 'string' || typeof vdom === 'number') {
return doc.createTextNode(vdom);
}
const {tag, props, children} = vdom;
// 1. 创建元素
const element = doc.createElement(tag);
// 2. 属性赋值
setProps(element, props);
// 3. 创建子元素
children.map(createElement)
.forEach(element.appendChild.bind(element));
return element;
}
// 属性赋值
function setProps(element, props) {
for (let key in props) {
element.setAttribute(key, props[key]);
}
}
@fuhaoliang
Copy link

compiled.js ?在哪里

@Arguseye
Copy link

Arguseye commented Apr 3, 2020

compiled.js ?在哪里

babel vdom_v1.js --out-file compiled.js

需要先安装babel-cli

@toassassin
Copy link

1
2
3

element.setAttribute(name, value),name='0'的时候报错,‘0’不是一个合法的属性值

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment