rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

Inject context and some builtin InjectionKeys

Open mdbetancourt opened this issue 5 years ago • 1 comments

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

mdbetancourt avatar Feb 21 '20 23:02 mdbetancourt

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 avatar Mar 14 '20 15:03 jods4

@jods4 FWIW You can get type-safe provide / inject in Vue via vue-atoms.

matthew-dean avatar Jul 21 '24 14:07 matthew-dean

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.

posva avatar Jul 21 '24 20:07 posva