0
0
Vueframework~30 mins

Events for child to parent communication in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Events for child to parent communication
📖 Scenario: You are building a simple Vue app where a child component sends a message to its parent when a button is clicked.
🎯 Goal: Create a child component that emits an event with a message. The parent component listens to this event and displays the message.
📋 What You'll Learn
Create a child component named MessageButton that emits an event called send-message with a string message.
In the parent component, listen for the send-message event from MessageButton.
Display the received message in the parent component.
Use Vue 3 Composition API with <script setup> syntax.
💡 Why This Matters
🌍 Real World
This pattern is common in Vue apps where child components need to notify parents about user actions or data changes, like form inputs or button clicks.
💼 Career
Understanding child-to-parent communication is essential for building interactive Vue applications and collaborating in teams that use component-based architecture.
Progress0 / 4 steps
1
Create the child component with a button
Create a Vue child component named MessageButton.vue with a button that says Click me. Use <script setup> and define the template with the button.
Vue
Need a hint?

Start by creating a button inside the template. No script logic needed yet.

2
Add event emission on button click
In MessageButton.vue, import defineEmits and create an emitter named emit. Add a click event to the button that calls emit('send-message', 'Hello from child').
Vue
Need a hint?

Use defineEmits to create an emitter and call it inside the button's click event.

3
Create the parent component and listen to the event
Create a parent component named App.vue. Import MessageButton. Add <MessageButton @send-message="handleMessage" /> in the template. Define a function handleMessage that receives the message and stores it in a reactive variable message.
Vue
Need a hint?

Use ref to create a reactive message variable. Define handleMessage to update it. Listen to send-message event on MessageButton.

4
Complete the app with proper component registration
Ensure MessageButton is imported and used in App.vue template. The app should show the message from the child when the button is clicked.
Vue
Need a hint?

Check that the child component is imported and used correctly. The message should update on button click.