Last active
September 14, 2021 02:35
-
-
Save dickenslian/86c4e266ae5f2134373376133bec9e3d to your computer and use it in GitHub Desktop.
你不知道对Virtual DOM(一)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} | |
} |
compiled.js ?在哪里
babel vdom_v1.js --out-file compiled.js
需要先安装babel-cli
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
compiled.js ?在哪里