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>)
//Parent.vue
<template>
<div>The parents value: {{this.providedValue}}</div>
<child />
</template>
<script lang="ts">
import { Component, Vue, Provide} from 'vue-property-decorator';
import Child from './Child.vue';
@Component({components: Child})
export default class Parent extends Vue {
@Provide('key') private providedValue: string = 'The value';
}
</script>
Now we've declared a value with the name key that can be consumed by all children, multiple levels deep:
//Child.vue
<template>
<div>The childs value: {{this.injectedValue}}</div>
</template>
<script lang="ts">
import { Component, Vue, Inject } from 'vue-property-decorator';
@Component
export default class Child extends Vue {
@Inject('key') private injectedValue!: string;
}
</script>
The property injectedValue will now be injected by Vue by walking up on the hierarchy until it finds a provided value with the key key.
If you want something dependency injection-like, it's best to provide the value at the top, where you create your Vue instance:
//index.ts
import Vue from 'vue';
//... imports and configs
new Vue({
el: '#app',
// Provide values by returning a key-value pair
provide: () => ({
'key1': 'value1',
'key2': 'value2'
}),
render: h => h(App)
});
Now you can use @Inject('key1') in any component of this Vue instance.