DEV Community

loading...
Cover image for How to pass data from child to parent in vue js

How to pass data from child to parent in vue js

freakflames29 profile image Sourav das Updated on ・1 min read

In this article I will show you how to pass data from child to parent in vue.
We know that if we want to send data from parent to child we can use props but for the reverse case we have to use a different approach to achieve this.
image

App.vue

<template>

  <h1>{{ title }}</h1>

  <Child @changeTitle="ChangeT($event)" />

</template>
<script>
import Child from "./components/Child"
export default{
name:'App',
components: {
    Child,
},
data()
{
   return{
     title:'Rick Grimes'
         }
},
methods:{
    ChangeT(title)
    {
      this.title=title;
    },
}
</script>
<style></style>
Enter fullscreen mode Exit fullscreen mode

Child.vue

<template lang="html">
  <button type="button" @click='passEvent'> Update me</button>
</template>

<script>
export default {
  name:'Child',
  methods:{
    passEvent()
    {
      this.$emit('changeTitle','Awesome ')
    }
  }
}
</script>

<style lang="css" scoped>
</style>
Enter fullscreen mode Exit fullscreen mode

In child.vue we are using a method named $emit this method takes 2 arguments first the custom event and the second is the data we are passing

  1. changeTitle is the custom event
  2. 'Awesome' is the data we are passing to parent

in App.vue we are calling a method named 'ChangeT($event)' on the event 'changeTitle' (it is custom event you can name as your preferences)

when the ChangeT function called it takes the parameter which we are passing from child in this case $event='Awesome'

then we are simply changes the data value with this $event value

Now we have successfully passed data from child to parent in vue

Discussion (0)

pic
Editor guide