From e79c918676a0703be868efce0115bc1037e84f40 Mon Sep 17 00:00:00 2001 From: Evan You Date: Tue, 5 Nov 2019 22:35:24 -0500 Subject: [PATCH] feat(inject): allow usage in functional components --- packages/runtime-core/src/apiInject.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/src/apiInject.ts b/packages/runtime-core/src/apiInject.ts index 23a620fed..de136d4a4 100644 --- a/packages/runtime-core/src/apiInject.ts +++ b/packages/runtime-core/src/apiInject.ts @@ -1,4 +1,5 @@ import { currentInstance } from './component' +import { currentRenderingInstance } from './componentRenderUtils' import { warn } from './warning' export interface InjectionKey extends Symbol {} @@ -31,8 +32,11 @@ export function inject( key: InjectionKey | string, defaultValue?: unknown ) { - if (currentInstance) { - const provides = currentInstance.provides + // fallback to `currentRenderingInstance` so that this can be called in + // a functional component + const instance = currentInstance || currentRenderingInstance + if (instance) { + const provides = instance.provides if (key in provides) { // TS doesn't allow symbol as index type return provides[key as string] @@ -42,6 +46,6 @@ export function inject( warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { - warn(`inject() can only be used inside setup().`) + warn(`inject() can only be used inside setup() or functional components.`) } }