Vue JS Emit function
Husniddin6939
Posted on November 16, 2024
We use Emit function for passing data from child component to Parent component and we are gonna show you to how it goes in codes
We start Emit function from child component
<template>
<div>
<div class="Child component">
<h1>d Component</h1>
<h2>{{ count }}</h2>
<button @click="sendDate">send count</button>
</div>
</div>
</template>
<script setup>
import {defineEmits, ref} from "vue";
const count=ref(0);
const emit=defineEmits();
const users=[
{
id:1,
name:"khusi",
age:20,
profession:"IT"
},
{
id:1,
name:"khusi",
age:20,
profession:"IT"
},
{
id:1,
name:"khusi",
age:20,
profession:"IT"
},
{
id:1,
name:"khusi",
age:20,
profession:"IT"
},
]
const sendDate=()=>{
emit("counter", 11);
emit("users", users);
}
</script>
Now we can pass them into Parent component
<template>
<div>
<div class="Parent component">
<h1>c Component</h1>
<ComponentD @counter="submitEmit" @users="submitUser"/>
</div>
</div>
</template>
<script setup>
import {defineEmits} from "vue";
import ComponentD from "./d-component.vue";
const emit=defineEmits();
const submitEmit=(e)=>{
console.log(e);
emit("counter", e)
}
const submitUser=(e)=>{
console.log(e);
emit("users", e);
}
</script>
the result is
Lets we learn how it works
- import {defineEmits, ref} from "vue"; Importing necessary things from vue
- const count=ref(0); creating a veriable and giving it default value with ref
- const emit=defineEmits(); It has to declared defineEmits in any veriable
- const users=[
{id:1, name:"khusi", age:20, profession:"IT"},
{id:1, name:"khusi", age:20, profession:"IT"},
{id:1, name:"khusi", age:20, profession:"IT"},
{id:1, name:"khusi", age:20, profession:"IT"},
] Using from any Data
- const sendDate=()=>{
emit("counter", 11);
emit("users", users);
} we create a function and give it in first optional number and the second our data inside of defineEmits and in the string we write optional name for using in Parent component
And we learn how to call them in Parent component
-const submitEmit=(e)=>{
console.log(e);
emit("counter", e)
}
-const submitUser=(e)=>{
console.log(e);
emit("users", e);
} Two function created and in it we call our emit variable from child component and give them its name and e. In this case e=Our optional number that 11 and our data
- <ComponentD @counter="submitEmit" @users="submitUser"/> Finally we call two function under emit optional names and we can see the results on console
Thank you All for attentions
Posted on November 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.