Skip to content

Instantly share code, notes, and snippets.

@IlCallo
Created January 13, 2022 18:10
Show Gist options
  • Save IlCallo/e578df6ce31358b01a224f25e82ea98d to your computer and use it in GitHub Desktop.
Save IlCallo/e578df6ce31358b01a224f25e82ea98d to your computer and use it in GitHub Desktop.
Inject stuff even outside components scope
import { App, InjectionKey } from 'vue';
/**
* Inject a service using Vue app reference and the injection key.
* Use this to inject a service when outside a component scope (eg. into a Quasar boot file),
* where Vue `inject` won't work.
* This is expecially useful when the data is provided from a third-party package
* which only expose the injection key.
*
* @example
* // src/boot/books.ts
* import { boot } from 'quasar/wrappers';
* import { BooksServiceInjectionKey } from 'book-manager';
*
* export default boot(({ app }) => {
* const booksService = appInject(app, BooksServiceInjectionKey);
* // ... business ah-ah ...
* })
*/
export function appInject<T>(app: App, injectionKey: InjectionKey<T>) {
return app._context.provides[
// Needs explicit casting to symbol, see: https://github.com/microsoft/TypeScript/issues/46956
// TODO: should be solved by https://github.com/vuejs/vue-next/pull/5089
injectionKey as symbol
] as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment