0
0
Vueframework~5 mins

Typing emits in Vue

Choose your learning style9 modes available
Introduction

Typing emits helps you tell Vue what events your component can send out. This makes your code safer and easier to understand.

When you create a Vue component that sends events to its parent.
When you want to catch mistakes early by checking event names and data types.
When you work in a team and want clear communication about component events.
When you use TypeScript with Vue to get better code completion and error checking.
Syntax
Vue
defineEmits<{ eventName: (payload: PayloadType) => void }>()
Use defineEmits inside the <script setup> block.
The object keys are event names, and the values are functions describing the payload.
Examples
This defines an event named update that sends a string value.
Vue
const emit = defineEmits<{ update: (value: string) => void }>()
This defines two events: close with no data, and select with a number.
Vue
const emit = defineEmits<{ close: () => void; select: (id: number) => void }>()
This defines events without payload types, just their names.
Vue
const emit = defineEmits(['open', 'save'])
Sample Program

This Vue component defines a submit event that sends a string. When the button is clicked, it emits the event with the name 'Alice'.

Vue
<script setup lang="ts">
const emit = defineEmits<{ submit: (name: string) => void }>()

function sendName() {
  emit('submit', 'Alice')
}
</script>

<template>
  <button @click="sendName">Send Name</button>
</template>
OutputSuccess
Important Notes

Typing emits helps catch errors if you try to emit an event that is not defined or with wrong data.

You can use both string array or object syntax, but object syntax gives better type safety.

Summary

Typing emits tell Vue what events your component can send.

This improves code safety and helps tools give better suggestions.

Use defineEmits inside <script setup> with event names and payload types.