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

Open
mdbetancourt opened this issue Feb 21, 2020 · 1 comment
Open

Inject context and some builtin InjectionKeys #131

mdbetancourt opened this issue Feb 21, 2020 · 1 comment

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.

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

2 participants