feat(inject): allow usage in functional components
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import { currentInstance } from './component'
|
import { currentInstance } from './component'
|
||||||
|
import { currentRenderingInstance } from './componentRenderUtils'
|
||||||
import { warn } from './warning'
|
import { warn } from './warning'
|
||||||
|
|
||||||
export interface InjectionKey<T> extends Symbol {}
|
export interface InjectionKey<T> extends Symbol {}
|
||||||
@@ -31,8 +32,11 @@ export function inject(
|
|||||||
key: InjectionKey<any> | string,
|
key: InjectionKey<any> | string,
|
||||||
defaultValue?: unknown
|
defaultValue?: unknown
|
||||||
) {
|
) {
|
||||||
if (currentInstance) {
|
// fallback to `currentRenderingInstance` so that this can be called in
|
||||||
const provides = currentInstance.provides
|
// a functional component
|
||||||
|
const instance = currentInstance || currentRenderingInstance
|
||||||
|
if (instance) {
|
||||||
|
const provides = instance.provides
|
||||||
if (key in provides) {
|
if (key in provides) {
|
||||||
// TS doesn't allow symbol as index type
|
// TS doesn't allow symbol as index type
|
||||||
return provides[key as string]
|
return provides[key as string]
|
||||||
@@ -42,6 +46,6 @@ export function inject(
|
|||||||
warn(`injection "${String(key)}" not found.`)
|
warn(`injection "${String(key)}" not found.`)
|
||||||
}
|
}
|
||||||
} else if (__DEV__) {
|
} else if (__DEV__) {
|
||||||
warn(`inject() can only be used inside setup().`)
|
warn(`inject() can only be used inside setup() or functional components.`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user