JAVASCRIPT
Vue 3 Component Communication with Props and Emits
Master parent-to-child data flow using `props` and child-to-parent event communication using `emits` in Vue 3 Composition API for modular components.
// ParentComponent.vue
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const message = ref('Hello from Parent!');
const childData = ref('');
const handleChildEvent = (data) => {
childData.value = data;
};
</script>
<template>
<div>
<h1>Parent Component</h1>
<p>Message for child: {{ message }}</p>
<p v-if="childData">Data from child: {{ childData }}</p>
<ChildComponent :parentMessage="message" @childEvent="handleChildEvent" />
</div>
</template>
// ChildComponent.vue
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
parentMessage: String
});
const emit = defineEmits(['childEvent']);
const sendDataToParent = () => {
emit('childEvent', 'Data from Child!');
};
</script>
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h2>Child Component</h2>
<p>Received from parent: {{ props.parentMessage }}</p>
<button @click="sendDataToParent">Send Data to Parent</button>
</div>
</template>
How it works: This snippet illustrates essential component communication patterns in Vue 3. The `ParentComponent` passes data down to `ChildComponent` using `props` (specifically `:parentMessage="message"`). The `ChildComponent` declares its expected props using `defineProps`. For child-to-parent communication, `ChildComponent` uses `defineEmits` to declare an event (`childEvent`) and then emits it (`emit('childEvent', 'Data from Child!')`). The `ParentComponent` listens for this event using `@childEvent="handleChildEvent"`, allowing it to react to actions or data originating from the child.