Composition API:
Dependency Injection
provide()
provide and inject enables dependency injection. Both can only be called during setup() with a current active instance.
Typing:
interface InjectionKey<T> extends Symbol {} function provide<T>(key: InjectionKey<T> | string, value: T): void // without default value function inject<T>(key: InjectionKey<T> | string): T | undefined // with default value function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T // with factory function inject<T>( key: InjectionKey<T> | string, defaultValue: () => T, treatDefaultAsFactory: true ): TVue provides an
InjectionKeyinterface which is a generic type that extendsSymbol. It can be used to sync the type of the injected value between the provider and the consumer:import { InjectionKey, provide, inject } from 'vue' const key: InjectionKey<string> = Symbol() provide(key, 'foo') // providing non-string value will result in error const foo = inject(key) // type of foo: string | undefinedIf using string keys or non-typed symbols, the type of the injected value will need to be explicitly declared:
const foo = inject<string>('foo') // string | undefinedSee also:
inject()
// TODO