I'm using Vue.js with TypeScript and the vue-property-decorator package. In theory I can do something like this, according to the documentation:
import { Component, Inject, Provide, Vue } from 'vue-property-decorator'
const s = Symbol('baz')
@Component
export class MyComponent extends Vue {
@Provide() foo = 'foo'
@Provide('bar') baz = 'bar'
@Inject() foo: string
@Inject('bar') bar: string
@Inject(s) baz: string
}
However, what if I want to use @Provide
and @Inject
on a class that is not a component? For example, if I have ComponentA
that depends on ServiceA
that depends on ServiceB
. How can i set this up?
You provide anything you want from a higher component by using the
@Provide
decorator and then ask for it in a lower component by using@Inject
. For example:In the parent component you provide the value using
@Provide(<someKey>)
Now we've declared a value with the name
key
that can be consumed by all children, multiple levels deep:The property
injectedValue
will now be injected by Vue by walking up on the hierarchy until it finds a provided value with the keykey
.If you want something dependency injection-like, it's best to provide the value at the top, where you create your Vue instance:
Now you can use
@Inject('key1')
in any component of this vue instance.