Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inject context and some builtin InjectionKeys #131

Closed
mdbetancourt opened this issue Feb 21, 2020 · 3 comments
Closed

Inject context and some builtin InjectionKeys #131

mdbetancourt opened this issue Feb 21, 2020 · 3 comments

Comments

@mdbetancourt
Copy link

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

@jods4
Copy link

jods4 commented Mar 14, 2020

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.

@matthew-dean
Copy link

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

@posva
Copy link
Member

posva commented Jul 21, 2024

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 posva closed this as completed Jul 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants