Vue JS (Provide, Inject)

husniddin6939

Husniddin6939

Posted on November 16, 2024

Vue JS (Provide, Inject)

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)
Enter fullscreen mode Exit fullscreen mode
<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");

Enter fullscreen mode Exit fullscreen mode

And the result is

Image description

Overall What we do is that

- import {provide} from "vue"; Provide imported by vue
Enter fullscreen mode Exit fullscreen mode
- import {reactive} from "vue"; Reactive imported by vue
Enter fullscreen mode Exit fullscreen mode
- const user=reactive({name:"Jahongir",age:30,}) Reactive Object created 
Enter fullscreen mode Exit fullscreen mode
- 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
Enter fullscreen mode Exit fullscreen mode

In Child element we accept the value with Inject like below

- import {inject} from "vue"; Inject imported by vue;
Enter fullscreen mode Exit fullscreen mode
- const user=inject("user"); user value from Parent component token by veriable with any optional name. 
Enter fullscreen mode Exit fullscreen mode
- 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"
Enter fullscreen mode Exit fullscreen mode
- <h2>{{ user }}</h2> Finally we run it so on 
Enter fullscreen mode Exit fullscreen mode

Thank you all for attentions

💖 💪 🙅 🚩
husniddin6939
Husniddin6939

Posted on November 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Vue JS (Provide, Inject)
vue Vue JS (Provide, Inject)

November 16, 2024