0
0
Vueframework~15 mins

Typing emits in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Typing emits in Vue 3
📖 Scenario: You are building a simple Vue 3 component that emits a typed event when a button is clicked. This helps other components know exactly what data to expect from the event.
🎯 Goal: Create a Vue 3 component that emits a typed event called update with a string payload when a button is clicked.
📋 What You'll Learn
Create a Vue 3 component using the <script setup> syntax
Define the emits option with a typed update event that accepts a string
Add a button that triggers the update event with a specific string payload
Use TypeScript to ensure the event payload is typed correctly
💡 Why This Matters
🌍 Real World
Typed emits help Vue developers build components that communicate clearly and safely, reducing bugs caused by unexpected event data.
💼 Career
Understanding typed emits is important for Vue developers working on scalable applications where components need strict contracts for events.
Progress0 / 4 steps
1
Create the Vue component skeleton
Create a Vue 3 component file with <script setup lang="ts"> and an empty template section.
Vue
Hint

Start by creating the basic structure of a Vue 3 component using the <script setup> syntax with TypeScript.

2
Define the typed emits option
Inside the <script setup lang="ts">, define a constant called emit using defineEmits with an event named update that accepts a string payload.
Vue
Hint

Use defineEmits with a TypeScript type that specifies the event name and the payload type.

3
Add a button that emits the event
In the <template>, add a <button> element with a click event handler that calls emit('update', 'Hello Vue').
Vue
Hint

Use the @click directive on the button to call the emit function with the correct event name and string.

4
Complete the component with proper typing
Ensure the component uses defineEmits with the typed update event and the button emits the event with the string 'Hello Vue'. The component should be fully typed and ready to use.
Vue
Hint

Check that the emits typing and button click event are correctly implemented and match exactly.