From 0952d4cf5183aec75fad551476d9538c9ad4f4ff Mon Sep 17 00:00:00 2001 From: Evan You Date: Wed, 19 Jun 2019 17:31:49 +0800 Subject: [PATCH] wip: provide/inject --- packages/runtime-core/src/apiInject.ts | 30 ++++++++++++++++++++++++++ packages/runtime-core/src/component.ts | 6 ++++-- packages/runtime-core/src/index.ts | 1 + 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 packages/runtime-core/src/apiInject.ts diff --git a/packages/runtime-core/src/apiInject.ts b/packages/runtime-core/src/apiInject.ts new file mode 100644 index 000000000..7c9e64eac --- /dev/null +++ b/packages/runtime-core/src/apiInject.ts @@ -0,0 +1,30 @@ +import { value, isValue, Value } from './apiState' +import { currentInstance } from './component' + +export interface Key extends Symbol {} + +export function provide(key: Key, value: T | Value) { + if (!currentInstance) { + // TODO warn + } else { + const provides = currentInstance.provides || (currentInstance.provides = {}) + provides[key as any] = value + } +} + +export function inject(key: Key): Value | undefined { + // traverse parent chain and look for provided value + if (!currentInstance) { + // TODO warn + } else { + let parent = currentInstance.parent + while (parent) { + const { provides } = parent + if (provides !== null && provides.hasOwnProperty(key as any)) { + const val = provides[key as any] + return isValue(val) ? val : value(val) + } + parent = parent.parent + } + } +} diff --git a/packages/runtime-core/src/component.ts b/packages/runtime-core/src/component.ts index 13ccb6d95..35886d68d 100644 --- a/packages/runtime-core/src/component.ts +++ b/packages/runtime-core/src/component.ts @@ -79,7 +79,7 @@ export interface FunctionalComponent

{ type LifecycleHook = Function[] | null -interface LifecycleHooks { +export interface LifecycleHooks { bm: LifecycleHook // beforeMount m: LifecycleHook // mounted bu: LifecycleHook // beforeUpdate @@ -110,8 +110,9 @@ export type ComponentInstance

= { next: VNode | null subTree: VNode update: ReactiveEffect - effects: ReactiveEffect[] | null render: RenderFunction | null + effects: ReactiveEffect[] | null + provides: Data | null // the rest are only for stateful components data: S @@ -193,6 +194,7 @@ export function createComponentInstance( rtc: null, ec: null, effects: null, + provides: null, // public properties data: EMPTY_OBJ, diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index 573259cab..ef37291a7 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -18,5 +18,6 @@ export { PropType, ComponentPropsOptions } from './componentProps' export * from './apiState' export * from './apiWatch' export * from './apiLifecycle' +export * from './apiInject' export * from './patchFlags' export * from './typeFlags'