Inject context and some builtin InjectionKeys
i think that should exists some builtin keys like ContextKey
const ContextKey: InjectionKey<SetupContext> = Symbol('tt')
so we can get context (store, router) through injection like
import { InjectionKeys } from 'vue'
function useProduct() {
const { root: { $store } } = inject(InjectionKeys.Context)
// do something with $store
}
this can make more modular "use" functions
FWIW vue-router solved this by exposing some useRoute and useRouter functions, so you can get the router like so:
import { useRouter } from 'vue-router'
function useStuff() {
const $router = useRouter()
}
Internally it's just:
import { inject } from 'vue'
export function useRouter() {
return inject('$ref')
}
It's easy to use and a bonus point is that it's strongly typed if you use TS.
The inject('$router') way is also strongly typed but only if you import 'vue-router', which you'd probably not do... so it's slightly inferior.
@jods4 FWIW You can get type-safe provide / inject in Vue via vue-atoms.
Not sure why this was open so long… These use* methods should be (and currently are) exposed by the corresponding libraries
@matthew-dean FYI, in case you missed, native inject also has a default value.