To pass data from a higher component to a lower one in Vue, you can use the @Provide
decorator to provide the data and then retrieve it using @Inject
. Here's an example:
In the parent component, use @Provide(<someKey>)
to provide the value.
//Parent.vue
<template>
<div>The parent's 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>
This declares a value with the name key
that can be accessed by all child components, regardless of depth:
//Child.vue
<template>
<div>The child's 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 be automatically injected by Vue by traversing up the hierarchy until it finds a matching key.
If you want a more dependency injection-like behavior, provide the values at the top level when creating your Vue instance:
//index.ts
import Vue from 'vue';
//... imports and configurations
new Vue({
el: '#app',
// Use provide option to return key-value pairs
provide: () => ({
'key1': 'value1',
'key2': 'value2'
}),
render: h => h(App)
});
Now you can access these values using @Inject('key1')
in any component within this Vue instance.