Created
January 13, 2022 18:10
-
-
Save IlCallo/e578df6ce31358b01a224f25e82ea98d to your computer and use it in GitHub Desktop.
Inject stuff even outside components scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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