How to Communicate from Child to Parent Using Events in Vue.js

In Vue.js, you can communicate from a child component to its parent component using events. This allows child components to emit custom events that the parent components can listen to and respond accordingly. Let's go through the process step by step with detailed code examples:

Emitting Events from Child Component

In the child component, you can emit custom events using the $emit method. This method emits an event with a specified name and optional data payload.

<!-- ChildComponent.vue -->
<template>
  <button @click="sendMessage">Send Message to Parent</button>
</template>

<script>
export default {
  methods: {
    sendMessage() {
      // Emitting custom event named 'message' with a data payload
      this.$emit('message', 'Hello from Child Component');
    }
  }
}
</script>

Listening to Events in Parent Component

In the parent component, you can listen to the custom event emitted by the child component using the v-on directive (or its shorthand @). You can specify the event name and the method to call when the event is triggered.

<!-- ParentComponent.vue -->
<template>
  <ChildComponent @message="handleMessage"></ChildComponent>
  <div>{{ receivedMessage }}</div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      receivedMessage: ''
    };
  },
  methods: {
    handleMessage(message) {
      // Update data in parent component
      this.receivedMessage = message;
    }
  }
}
</script>

In this example

  • The child component emits a custom event named 'message' when the button is clicked, passing along the message 'Hello from Child Component'.
  • The parent component listens to the 'message' event emitted by the child component using the @message directive. When the event is triggered, the handleMessage method is called, which updates the receivedMessage data property in the parent component.
  • The parent component's template then displays the receivedMessage.

This way, the child component can communicate with its parent component by emitting custom events, allowing for a flexible and dynamic interaction between components in a Vue.js application.