JAVASCRIPT
Vue 3 Component Communication: Props and Custom Events
Master data flow in Vue 3 using props for parent-to-child communication and custom `emit` events for child-to-parent interaction.
<!-- ParentComponent.vue -->
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentMessage = ref('Hello from Parent!');
const childResponse = ref('');
function handleChildEvent(message) {
childResponse.value = `Child responded: "${message}"`;
}
</script>
<template>
<h1>Parent Component</h1>
<p>Parent Message: {{ parentMessage }}</p>
<p v-if="childResponse">{{ childResponse }}</p>
<ChildComponent
:messageFromParent="parentMessage"
@childSaidHello="handleChildEvent"
/>
</template>
<!-- ChildComponent.vue -->
<script setup>
import { defineProps, defineEmits } from 'vue';
// Define props received from parent
const props = defineProps({
messageFromParent: String
});
// Define custom events that can be emitted
const emit = defineEmits(['childSaidHello']);
function sayHelloToParent() {
emit('childSaidHello', 'Hi Parent, I received your message!');
}
</script>
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h3>Child Component</h3>
<p>Received from parent: "{{ props.messageFromParent }}"</p>
<button @click="sayHelloToParent">Say Hello Back to Parent</button>
</div>
</template>
How it works: This snippet illustrates essential component communication in Vue 3. The `ParentComponent` passes data down to `ChildComponent` using props (e.g., `:messageFromParent`). The `ChildComponent` receives these props via `defineProps`. To communicate back, the `ChildComponent` uses `defineEmits` to declare custom events and `emit()` to trigger them (e.g., `@childSaidHello`), which the parent can listen to and handle. This establishes a clear, unidirectional data flow.