Skip to content

Commit

Permalink
feat: add access setupState
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Feb 8, 2021
1 parent 4ff00ff commit eb09e93
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/runtime-core/component.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { initProps } from "./componentProps";
import { emit } from "./componentEmits";
import { PublicInstanceProxyHandlers } from "./componentPublicInstance";
import { proxyRefs } from "@vue/reactivity";
export function createComponentInstance(vnode) {
const instance = {
type: vnode.type,
Expand All @@ -11,6 +12,7 @@ export function createComponentInstance(vnode) {
attrs: {}, // 存放 attrs 的数据
slots: {}, // 存放插槽的数据
ctx: {}, // context 对象
setupState: {}, // 存储 setup 的返回值
emit: () => {},
};

Expand Down Expand Up @@ -95,7 +97,13 @@ function handleSetupResult(instance, setupResult) {
} else if (typeof setupResult === "object") {
// 返回的是一个对象的话
// 先存到 setupState 上
instance.setupState = setupResult;
// 先使用 @vue/reactivity 里面的 proxyRefs
// 后面我们自己构建
// proxyRefs 的作用就是把 setupResult 对象做一层代理
// 方便用户直接访问 ref 类型的值
// 比如 setupResult 里面有个 count 是个 ref 类型的对象,用户使用的时候就可以直接使用 count 了,而不需要在 count.value
// 这里也就是官网里面说到的自动结构 Ref 类型
instance.setupState = proxyRefs(setupResult);
}

finishComponentSetup(instance);
Expand Down
9 changes: 9 additions & 0 deletions src/runtime-core/componentPublicInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,17 @@ export const PublicInstanceProxyHandlers = {
// 用户访问 proxy[key]
// 这里就匹配一下看看是否有对应的 function
// 有的话就直接调用这个 function
const { setupState } = instance;
console.log(`触发 proxy hook , key -> : ${key}`);

if (key !== "$") {
// 说明不是访问 public api
// 先检测访问的 key 是否存在于 setupState 中, 是的话直接返回
if (key in setupState) {
return setupState[key];
}
}

const publicGetter = publicPropertiesMap[key];

if (publicGetter) {
Expand Down
4 changes: 3 additions & 1 deletion src/runtime-core/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,9 @@ function setupRenderEffect(instance, container) {
// 主要就是拿到新的 vnode ,然后和之前的 vnode 进行对比
console.log("调用更新逻辑");
// 拿到最新的 subTree
const nextTree = instance.render(instance.proxy);

const proxyToUse = instance.proxy;
const nextTree = instance.render.call(proxyToUse, proxyToUse);
// 替换之前的 subTree
const prevTree = instance.subTree;
instance.subTree = nextTree;
Expand Down

0 comments on commit eb09e93

Please sign in to comment.