wip: adjust inject API

This commit is contained in:
Evan You 2019-08-19 14:45:11 -04:00
parent 145bf98840
commit 685348f818

View File

@ -1,9 +1,8 @@
import { ref, isRef, Ref } from './apiState'
import { currentInstance } from './component' import { currentInstance } from './component'
export interface InjectionKey<T> extends Symbol {} export interface InjectionKey<T> extends Symbol {}
export function provide<T>(key: InjectionKey<T> | string, value: T | Ref<T>) { export function provide<T>(key: InjectionKey<T> | string, value: T) {
if (!currentInstance) { if (!currentInstance) {
// TODO warn // TODO warn
} else { } else {
@ -22,19 +21,16 @@ export function provide<T>(key: InjectionKey<T> | string, value: T | Ref<T>) {
} }
} }
export function inject<T>(key: InjectionKey<T> | string): Ref<T> | undefined export function inject<T>(key: InjectionKey<T> | string): T | undefined
export function inject<T>( export function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T
key: InjectionKey<T> | string,
defaultValue: T
): Ref<T>
export function inject(key: InjectionKey<any> | string, defaultValue?: any) { export function inject(key: InjectionKey<any> | string, defaultValue?: any) {
if (!currentInstance) { if (!currentInstance) {
// TODO warn // TODO warn
} else { } else {
// TODO should also check for app-level provides // TODO should also check for app-level provides
const provides = currentInstance.parent && currentInstance.provides const provides = currentInstance.parent && currentInstance.provides
const val = return provides && key in provides
provides && key in provides ? (provides[key as any] as any) : defaultValue ? (provides[key as any] as any)
return isRef(val) ? val : ref(val) : defaultValue
} }
} }