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

60 lines
2.1 KiB
TypeScript
Raw Normal View History

import { isFunction } from '@vue/shared'
2019-06-19 17:31:49 +08:00
import { currentInstance } from './component'
import { currentRenderingInstance } from './componentRenderUtils'
2019-08-21 03:51:55 +08:00
import { warn } from './warning'
2019-06-19 17:31:49 +08:00
export interface InjectionKey<T> extends Symbol {}
2019-06-19 17:31:49 +08:00
2019-08-20 02:45:11 +08:00
export function provide<T>(key: InjectionKey<T> | string, value: T) {
2019-06-19 17:31:49 +08:00
if (!currentInstance) {
if (__DEV__) {
2019-09-04 06:11:04 +08:00
warn(`provide() can only be used inside setup().`)
}
2019-06-19 17:31:49 +08:00
} 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-10-09 00:43:13 +08:00
// TS doesn't allow symbol as index type
provides[key as string] = value
2019-06-19 17:31:49 +08:00
}
}
2019-08-20 02:45:11 +08:00
export function inject<T>(key: InjectionKey<T> | string): T | undefined
export function inject<T>(
key: InjectionKey<T> | string,
defaultValue: T,
treatDefaultAsFactory?: boolean
): T
2019-10-22 23:26:48 +08:00
export function inject(
key: InjectionKey<any> | string,
defaultValue?: unknown,
treatDefaultAsFactory = false
2019-10-22 23:26:48 +08:00
) {
// fallback to `currentRenderingInstance` so that this can be called in
// a functional component
const instance = currentInstance || currentRenderingInstance
if (instance) {
const provides = instance.provides
2020-08-21 05:48:28 +08:00
if ((key as string | symbol) in provides) {
2019-10-09 00:43:13 +08:00
// TS doesn't allow symbol as index type
return provides[key as string]
} else if (arguments.length > 1) {
return treatDefaultAsFactory && isFunction(defaultValue)
? defaultValue()
: defaultValue
2019-08-21 03:51:55 +08:00
} else if (__DEV__) {
warn(`injection "${String(key)}" not found.`)
2019-08-21 03:51:55 +08:00
}
2019-09-04 06:11:04 +08:00
} else if (__DEV__) {
warn(`inject() can only be used inside setup() or functional components.`)
2019-06-19 17:31:49 +08:00
}
}