We use Provide and Inject for transporting Data from Parent element to any child elements directly and in this code I will show you how to use them
<template>
<h1>Parent Component</h1>
<div class="wrapper">
<h1>{{ user }}</h1>
<input type="text" placeholder="Enter username" v-model="user.name">
<ComponentD :user="user"/>
</div>
</template>
import {reactive,provide} from "vue";
const user=reactive({
name:"Jahongir",
age:30,
})
provide("user", user)
<template>
<div>
<div class="child-element">
<h1>d Component</h1>
<h2>{{ user }}</h2>
</div>
</div>
</template>
<script setup>
import {inject} from "vue";
const user=inject("user");
And the result is
Overall What we do is that
- import {provide} from "vue"; Provide imported by vue
- import {reactive} from "vue"; Reactive imported by vue
- const user=reactive({name:"Jahongir",age:30,}) Reactive Object created
- provide("user", user); In this case, first user in the string is optional name and the second value is our object that we should not be changed
In Child element we accept the value with Inject like below
- import {inject} from "vue"; Inject imported by vue;
- const user=inject("user"); user value from Parent component token by veriable with any optional name.
- For example in the above we would write any names after const but we should give inside of inject provide's first string name "user"
- <h2>{{ user }}</h2> Finally we run it so on
Thank you all for attentions
Top comments (0)