0
0
Vueframework~30 mins

Emitting custom events in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Emitting Custom Events in Vue
📖 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 a custom 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 with a button.
Add a string variable message in the child component with the value 'Hello from child!'.
Emit a custom event named send-message with the message when the button is clicked.
In the parent component, listen for the send-message event and display the received message.
💡 Why This Matters
🌍 Real World
Custom events let components talk to each other in Vue apps, like a child telling a parent when something happens.
💼 Career
Understanding event emission is key for building interactive Vue applications and collaborating in teams.
Progress0 / 4 steps
1
Create the child component with a message
Create a Vue component named MessageButton using <script setup>. Inside it, define a constant string variable called message with the value 'Hello from child!'. Also add a button element with the text Send Message inside the template.
Vue
Need a hint?

Use const message = 'Hello from child!' inside the <script setup> block.

2
Add event emission on button click
In the MessageButton component, import defineEmits from Vue. Create an emitter named emit using defineEmits(['send-message']). Add a click event listener to the button that calls emit('send-message', message).
Vue
Need a hint?

Use defineEmits(['send-message']) and add @click on the button to emit the event.

3
Create the parent component and listen for the event
Create a parent Vue component using <script setup>. Import the MessageButton component. Define a reactive variable receivedMessage initialized as an empty string. In the template, include <MessageButton /> and listen for the send-message event with a handler that sets receivedMessage to the event payload. Below the button, display receivedMessage inside a paragraph.
Vue
Need a hint?

Use ref('') for receivedMessage and define a function handleMessage to update it.

4
Complete the app by exporting the parent component
Ensure the parent component exports correctly and includes the MessageButton component in its components list if needed. Confirm the template and script setup are properly closed.
Vue
Need a hint?

Make sure the component code is complete and properly structured.