JAVASCRIPT

Communicate Between Child and Parent Components with Vue 3 Custom Events

Understand how to emit custom events from child components and listen for them in parent components using Vue 3's `defineEmits` and `@event-name` syntax for clear communication.

// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <p>Last message from child: {{ childMessage }}</p>
    <ChildComponent @messageEmitted="handleChildMessage" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const childMessage = ref('');

const handleChildMessage = (message) => {
  childMessage.value = message;
  console.log('Received message from child:', message);
};
</script>

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <button @click="sendMessage">Send Message to Parent</button>
  </div>
</template>

<script setup>
import { defineEmits } from 'vue';

// Declare the events this component can emit
const emit = defineEmits(['messageEmitted']);

const sendMessage = () => {
  const msg = 'Hello from the child!';
  // Emit the custom event with a payload
  emit('messageEmitted', msg);
};
</script>
How it works: In Vue 3, custom events are the primary way for a child component to communicate with its parent. The child component uses `defineEmits` to declare the events it can emit and then calls the returned `emit` function, passing the event name and any payload data. The parent component then listens for this custom event using the `v-on` directive (shorthand `@`) in its template. This clear, explicit event-driven pattern ensures decoupled and maintainable component interactions, allowing the child to notify the parent about actions or state changes without knowing the parent's internal logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs