In Vue.js 2, you can use custom events to send messages from a child component to a parent component. Here’s how you can do it:

1. Parent Component:

The parent component will listen for events emitted by the child component. You can define the custom event handler on the parent and bind it to the child component.

<template>
  <div>
    <child-component @custom-event="handleCustomEvent"></child-component>
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleCustomEvent(message) {
      console.log('Received message from child:', message);
    }
  }
};
</script>
  • @custom-event is the shorthand for v-on:custom-event, which listens for the custom-event from the child component.
  • When the child component emits the custom-event, the handleCustomEvent method in the parent will be triggered, and the data passed from the child will be received.

2. Child Component:

In the child component, you use $emit to send an event to the parent. The custom-event is emitted, and you can send additional data along with it.



  • When the button in the child is clicked, the sendEventToParent method is called, and it uses this.$emit() to emit an event named custom-event.
  • The second argument (‘Hello Parent!’) is the data that is passed to the parent component. In this case, it’s a simple string.

3. Communication Flow:

  • The child component emits an event (custom-event).
  • The parent component listens for that event using @custom-event=”handleCustomEvent”.
  • When the event is received, the parent runs the handleCustomEvent method with the data passed from the child.

Full Example:

Parent Component:



Child Component:




Conclusion:

This is a simple and effective way to pass data from a child component to a parent component in Vue 2. You can emit custom events from the child and handle them in the parent using @event-name syntax in the parent template.

Need Help With Vue Development?

Work with our skilled Vue developers to accelerate your project and boost its performance.

Hire Vuejs Developers

Support On Demand!

Related Q&A