How to pass data from child to parent component in Vue JS

In this post, we will learn how to pass data from child to parent component in Vue JS.

In Vue we can pass data between two components in two ways:

  1. From parent to child using props, and
  2. From child to parent using the $emit function.

Read how to send data from parent to child component : How to pass data from parent to child using props in Vue

Now, to send data from the child to the parent we will use $emit function in Vue.

Le’s see an example to achieve this.

Suppose we have a form in our child component and we need to pass the data to the parent component.

Form.vue (Child Component)

<template>
  <div class="form">
    <form @submit.prevent>
      <input type="text" v-model="name" placeholder="name" />
      <input type="text" v-model="email" placeholder="Email" />
      <button type="submit" @click="submitData">Submit</button>
    </form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      email: "",
    };
  },
  methods: {
    submitData(e) {
      this.$emit("passData", { name: this.name, emial: this.email });
    },
  },
};
</script>

Here, in the child component we have a form with two input fields: Name and Email and a Submit button.

And we have a function called submitData(), which is called when the submit button is clicked.

The $emit function in Vue is used to emit custom events. It takes two arguments, the first is the custom event and the second argument is the data we are passing to the parent component.

Here, passData is the custom event and we are passing an object with the name and the email as the data to the parent component.

Next, we have to import this child component (Form.vue) to the parent component (App.vue)

App.vue (Parent Component)

<template>
  <div id="app">
    <Form @passData="GetData($event)" />
    <div>
      <h4>Data in Parent Component:</h4>
      {{ personInfo }}
    </div>
  </div>
</template>

<script>
import Form from "./components/Form";

export default {
  name: "App",
  data() {
    return {
      personInfo: "",
    };
  },
  components: {
    Form,
  },
  methods: {
    GetData(data) {
      this.personInfo = data;
    },
  },
};
</script>

In the Parent component (App.vue), we have called a function GetData($event) on the custom event (@passData) we have passed from the child component.

When the data is passed, the GetData() function is called and it takes all the data (here, name and email) passed from the child component.

The received data is assigned to the data property personInfo and displayed it on the template.

Demo:

pass data from child to parent component in Vue

Edit pass-data-child-to-parent-vue

Related Topics:

How to get data from the child component in Vue

Scroll to Top