vue3-core/packages/runtime-core/src/apiInject.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2019-06-19 17:31:49 +08:00
import { value, isValue, Value } from './apiState'
import { currentInstance } from './component'
export interface Key<T> extends Symbol {}
export function provide<T>(key: Key<T> | string, value: T | Value<T>) {
2019-06-19 17:31:49 +08:00
if (!currentInstance) {
// TODO warn
} else {
2019-06-19 22:48:22 +08:00
let provides = currentInstance.provides
// by default an instance inherits its parent's provides object
// but when it needs to provide values of its own, it creates its
// own provides object using parent provides object as prototype.
// this way in `inject` we can simply look up injections from direct
// parent and let the prototype chain do the work.
const parentProvides =
currentInstance.parent && currentInstance.parent.provides
if (parentProvides === provides) {
provides = currentInstance.provides = Object.create(parentProvides)
}
2019-06-19 17:31:49 +08:00
provides[key as any] = value
}
}
export function inject<T>(key: Key<T> | string): Value<T> | undefined {
2019-06-19 17:31:49 +08:00
if (!currentInstance) {
// TODO warn
} else {
2019-06-19 22:50:14 +08:00
// TODO should also check for app-level provides
2019-06-19 22:48:22 +08:00
const provides = currentInstance.parent && currentInstance.provides
if (provides) {
const val = provides[key as any] as any
2019-06-19 22:48:22 +08:00
return isValue(val) ? val : value(val)
2019-06-19 17:31:49 +08:00
}
}
}