Skip to content

Commit

Permalink
feat: add component update logic
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed May 6, 2021
1 parent 53b085e commit 4b0f8de
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/runtime-core/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function createComponentInstance(vnode, parent) {
const instance = {
type: vnode.type,
vnode,
next: null, // 需要更新的 vnode,用于更新 component 类型的组件
props: {},
parent,
provides: parent ? parent.provides : {}, // 获取 parent 的 provides 作为当前组件的初始化值 这样就可以继承 parent.provides 的属性了
Expand Down
1 change: 1 addition & 0 deletions src/runtime-core/componentPublicInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const publicPropertiesMap = {
// i 就是 instance 的缩写 也就是组件实例对象
$emit: (i) => i.emit,
$slots: (i) => i.slots,
$props: (i) => i.props,
};

// todo 需要让用户可以直接在 render 函数内直接使用 this 来触发 proxy
Expand Down
18 changes: 17 additions & 1 deletion src/runtime-core/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ function updateComponent(n1, n2, container) {
// 在update 中调用的 next 就变成了 n2了
// ps:可以详细的看看 update 中 next 的应用
// TODO 需要在 update 中处理支持 next 的逻辑
// instance.update();
instance.update();
} else {
console.log(`组件不需要更新: ${instance}`);
// 不需要更新的话,那么只需要覆盖下面的属性即可
Expand Down Expand Up @@ -435,6 +435,14 @@ function setupRenderEffect(instance, container) {
// 主要就是拿到新的 vnode ,然后和之前的 vnode 进行对比
console.log("调用更新逻辑");
// 拿到最新的 subTree
const { next, vnode } = instance;

// 如果有 next 的话, 说明需要更新组件的数据(props,slots 等)
// 先更新组件的数据,然后更新完成后,在继续对比当前组件的子元素
if (next) {
next.el = vnode.el;
updateComponentPreRender(instance, next);
}

const proxyToUse = instance.proxy;
const nextTree = instance.render.call(proxyToUse, proxyToUse);
Expand Down Expand Up @@ -462,3 +470,11 @@ function setupRenderEffect(instance, container) {
}
);
}

function updateComponentPreRender(instance, nextVNode) {
const { props } = nextVNode;
console.log("更新组件的 props", props);
instance.props = props;
console.log("更新组件的 slots");
// TODO 更新组件的 slots
}

0 comments on commit 4b0f8de

Please sign in to comment.