process-component

第一步

packages/runtime-core/src/createVnode.ts

1
2
3
4
5
6
7
8
9
10
11
import { isObject, isString, ShapeFlags } from '@vue/shared';

export function createVnode(type, props, children?) {
// -----------------------------新增开始-----------------------------
const shapeFlag = isString(type) ? ShapeFlags.ELEMENT : isObject(type) ? ShapeFlags.STATEFUL_COMPONENT : 0;
// -----------------------------新增结束-----------------------------

...
return vnode;
}

packages/runtime-core/src/renderer.ts

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
69
70
export function createRenderer(renderOptions) {

const mountComponent = (n1, n2, container, anchor) => {
// 组件可以基于自己的状态重新渲染
const {
data = () => {
}, render
} = n2.type;

// 组件的状态
const state = reactive(data());

const instance = {
state,
vnode: n2,
subTree: null,
isMounted: false,
update: null
};

const componentUpdateFn = () => {
if (!instance.isMounted) {
const subTree = render.call(state, state);
patch(null, subTree, container, anchor);
instance.isMounted = true;
instance.subTree = subTree;
} else {
const subTree = render.call(state, state);
patch(instance.subTree, subTree, container, anchor);

}
};
const effect = new ReactiveEffect(componentUpdateFn, () => update());

const update = instance.update = () => {
effect.run();
};
update();
};

const processComponent = (n1, n2, container, anchor) => {
if (n1 === null) {
// 组件的渲染
mountComponent(n1, n2, container, anchor);
} else {
// 组件更新
}
};

const patch = (n1, n2, container, anchor = null) => {
const { type, shapeFlag } = n2;

switch (type) {
case Text:
processText(n1, n2, container);
break;
case Fragment:
processFragment(n1, n2, container);
break;
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
// 处理元素
processElement(n1, n2, container, anchor);
} else if (shapeFlag & ShapeFlags.COMPONENT) {
// 处理组件
processComponent(n1, n2, container, anchor);
}
}
}
}