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