From: Evan You Date: Wed, 6 Nov 2019 03:35:24 +0000 (-0500) Subject: feat(inject): allow usage in functional components X-Git-Tag: v3.0.0-alpha.0~234 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=e79c918676a0703be868efce0115bc1037e84f40;p=thirdparty%2Fvuejs%2Fcore.git feat(inject): allow usage in functional components --- diff --git a/packages/runtime-core/src/apiInject.ts b/packages/runtime-core/src/apiInject.ts index 23a620fedd..de136d4a47 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.`) } }