Skip to content

Instantly share code, notes, and snippets.

@dickenslian dickenslian/vdom_v1.html
Last active Aug 23, 2018

Embed
What would you like to do?
你不知道对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]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.