Emit data in Vue.js

Emit data in Vue.js

emits.png

In Vue.js, custom events helps to communicate with your parent components enabling to send data.

In this tutorial,we’ll learn how to communicate and send data from child component to parent component. Let's begin!

Let us consider a scenario of opening and closing a greeting on click of a button.

Step 1: Create a child component for greet message.

<template>
  <div>
    <h2>This is a greeting message</h2>
    <button>Close</button>
  </div>
</template>

<script>
  export default {
    name: 'greet'
  }
</script>

Step 2: Back in parent component(App.vue), import the component and display the component using conditional rendering with a v-show for a data property. Set the initial state of data object showGreet as false. Upon click of the button, it is set to true using v-show directive.

Template block:

 <div id="app">
    <button @click="showGreet = true">Show pop-up window</button>
    <Greet v-show="showGreet" />
  </div>

Script block:

import Greet from "./components/greet.vue";

export default {
  name: "App",
  components: {
    Greet,
  },
  data() {
    return {
      showGreet: false
    }
  }
}

Step 3: Add an emits option which is an array of event that a child component can emit to parent. Let us add an event named close. Use event binding to add click event. We use a special instance variable $emit to emit a custom event to the parent component.

Template section:

 <button @click="$emit('close')">Close</button>

Scripts section:

 emits: ['close']

Step 4: In the parent component, we need to listen to the close event. In the button, we add custom event instead of a dom event. Upon clicking this event, we make the showGreet back to false. Update the Greet component in App.vue

 <Greet v-show="showGreet" @close="showGreet=false"/>

Before close event:

greet.png

Upon clicking the button:

greet2.png It's hidden now! We could successfully communicate from child to the parent.

Step 5: Now let us pass data from child to parent. Pass in the data as the second argument in the $emit event which would be the data to be sent. Let us send 'programmer' to the parent. In Greet.vue edit the $event in button tag:

 <button @click="$emit('close', 'programmer')">Close</button>

In templates section of app.vue:

 <Greet v-show="showGreet" @close="closeGreet"/>

In the scripts section, create the method closeGreet which is initialized to close custom event.

methods: {
    closeGreet(name) {
      this.showGreet = false,
      console.log('Name:',name);
    }
  }

And that's it!! We've managed to pass data from child to parent by emitting an event using $emit property. Hope you've found this useful. Let me know your thoughts in the comments.

Happy coding :D