]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(inject): allow usage in functional components
authorEvan You <yyx990803@gmail.com>
Wed, 6 Nov 2019 03:35:24 +0000 (22:35 -0500)
committerEvan You <yyx990803@gmail.com>
Wed, 6 Nov 2019 17:51:26 +0000 (12:51 -0500)
packages/runtime-core/src/apiInject.ts

index 23a620fedd46e861ed9aa12ed42d6d7a796ec045..de136d4a4748544bfe0805744f104efbf5c634c4 100644 (file)
@@ -1,4 +1,5 @@
 import { currentInstance } from './component'
+import { currentRenderingInstance } from './componentRenderUtils'
 import { warn } from './warning'
 
 export interface InjectionKey<T> extends Symbol {}
@@ -31,8 +32,11 @@ export function inject(
   key: InjectionKey<any> | 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.`)
   }
 }