11import { ComponentInstance } from '../component' ;
2- import { ensureCurrentVMInFn } from '../helper' ;
2+ import { currentVMInFn } from '../helper' ;
33import { hasOwn , warn } from '../utils' ;
4+ import { getCurrentVM } from '../runtimeContext' ;
45
56const NOT_FOUND = { } ;
67export interface InjectionKey < T > extends Symbol { }
78
8- function resolveInject ( provideKey : InjectionKey < any > , vm : ComponentInstance ) : any {
9+ function resolveInject ( provideKey : InjectionKey < any > | string , vm : ComponentInstance ) : any {
910 let source = vm ;
1011 while ( source ) {
1112 // @ts -ignore
@@ -20,12 +21,14 @@ function resolveInject(provideKey: InjectionKey<any>, vm: ComponentInstance): an
2021}
2122
2223export function provide < T > ( key : InjectionKey < T > | string , value : T ) : void {
23- const vm : any = ensureCurrentVMInFn ( 'provide' ) ;
24+ const vm : any = currentVMInFn ( 'provide' ) ;
25+ if ( ! vm ) return ;
26+
2427 if ( ! vm . _provided ) {
2528 const provideCache = { } ;
2629 Object . defineProperty ( vm , '_provided' , {
2730 get : ( ) => provideCache ,
28- set : v => Object . assign ( provideCache , v ) ,
31+ set : ( v ) => Object . assign ( provideCache , v ) ,
2932 } ) ;
3033 }
3134
@@ -34,19 +37,23 @@ export function provide<T>(key: InjectionKey<T> | string, value: T): void {
3437
3538export function inject < T > ( key : InjectionKey < T > | string ) : T | undefined ;
3639export function inject < T > ( key : InjectionKey < T > | string , defaultValue : T ) : T ;
37- export function inject < T > ( key : InjectionKey < T > | string , defaultValue ?: T ) : T | undefined {
40+ export function inject ( key : InjectionKey < any > | string , defaultValue ?: unknown ) {
3841 if ( ! key ) {
3942 return defaultValue ;
4043 }
4144
42- const vm = ensureCurrentVMInFn ( 'inject' ) ;
43- const val = resolveInject ( key as InjectionKey < T > , vm ) ;
44- if ( val !== NOT_FOUND ) {
45- return val ;
46- } else {
47- if ( defaultValue === undefined && process . env . NODE_ENV !== 'production' ) {
48- warn ( `Injection "${ String ( key ) } " not found` , vm ) ;
45+ const vm = getCurrentVM ( ) ;
46+ if ( vm ) {
47+ const val = resolveInject ( key , vm ) ;
48+ if ( val !== NOT_FOUND ) {
49+ return val ;
50+ } else {
51+ if ( defaultValue === undefined && process . env . NODE_ENV !== 'production' ) {
52+ warn ( `Injection "${ String ( key ) } " not found` , vm ) ;
53+ }
54+ return defaultValue ;
4955 }
50- return defaultValue ;
56+ } else {
57+ warn ( `inject() can only be used inside setup() or functional components.` ) ;
5158 }
5259}
0 commit comments