What Is inject in Vue?

Vue's inject option is the mechanism that passes values from a parent component down to its children. It is a convenient way to share data or functions between components.
inject is used to receive values that a component makes available with provide. provide supplies values to every component below it in the tree. Here is a simple example:
<!-- ParentComponent.vue -->
<template>
<div>
<child-component />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
provide() {
return {
message: 'Hello, I am sharing this value!',
};
},
};
</script><!-- ChildComponent.vue -->
<template>
<div>
<p>{{ injectedMessage }}</p>
</div>
</template>
<script>
export default {
inject: ['message'],
computed: {
injectedMessage() {
return this.message;
},
},
};
</script>ParentComponent provides a value called message to all its descendants with provide. ChildComponent receives it with inject and uses it through the injectedMessage computed property, so it can read the message that comes from ParentComponent.
This mechanism makes sharing data and communicating between components easier.
Have a question about this article? Write to me


