-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrendererTest.js
68 lines (64 loc) · 1.42 KB
/
rendererTest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function vcomponentFun() {
return {
tag: 'h2',
props: {
onClick: () => {
alert('hello world');
},
},
children: '我是vue渲染出来的标题fun',
};
}
const vcomponentObj = {
render() {
return {
tag: 'h2',
props: {
onClick: () => {
alert('hello world');
},
},
children: '我是vue渲染出来的标题obj',
};
},
};
const vnode = {
tag: vcomponentObj,
};
function renderer(vnode, container) {
if (typeof vnode.tag === 'string') {
mountElement(vnode, container);
} else if (typeof vnode.tag === 'function') {
mountComponentFun(vnode, container);
} else if (typeof vnode.tag === 'object') {
mountComponentObj(vnode, container);
}
}
function mountElement(vnode, container) {
const el = document.createElement(vnode.tag);
for (let key in vnode.props) {
if (/^on/.test(key)) {
el.addEventListener(
key.substring(2).toLowerCase(),
vnode.props[key]
);
}
}
if (typeof vnode.children === 'string') {
el.appendChild(document.createTextNode(vnode.children));
} else if (Array.isArray(vnode.children)) {
vnode.children.forEach((v) => {
renderer(v, el);
});
}
container.appendChild(el);
}
function mountComponentFun(vnode, container) {
const subtree = vnode.tag();
renderer(subtree, container);
}
function mountComponentObj(vnode, container) {
const subtree = vnode.tag.render();
renderer(subtree, container);
}
renderer(vnode, document.getElementById('app'));