0
0
VueHow-ToBeginner · 4 min read

How to Define Emits in Script Setup in Vue 3

In Vue 3's script setup, you define emits by using the defineEmits function, which declares the events your component can emit. You call the returned function to emit events, like emit('eventName', payload).
📐

Syntax

The defineEmits function is used inside the <script setup> block to declare which events the component can emit. It returns an emit function that you use to trigger those events.

You can define emits as an array of event names or as an object with event names and validators.

vue
<script setup>
const emit = defineEmits(['update', 'delete'])

// or with validators
const emit = defineEmits({
  update: (payload) => typeof payload === 'string',
  delete: null
})
</script>
💻

Example

This example shows a button component that emits a click event when pressed. The parent listens and reacts to it.

vue
<!-- ChildButton.vue -->
<script setup>
const emit = defineEmits(['click'])

function handleClick() {
  emit('click')
}
</script>

<template>
  <button @click="handleClick">Click me</button>
</template>

<!-- ParentComponent.vue -->
<script setup>
import ChildButton from './ChildButton.vue'

function onChildClick() {
  alert('Button clicked!')
}
</script>

<template>
  <ChildButton @click="onChildClick" />
</template>
Output
When the button is clicked, an alert box shows 'Button clicked!'
⚠️

Common Pitfalls

  • Not using defineEmits causes Vue to warn about undeclared emits.
  • Emitting events with wrong names or typos means the parent won't catch them.
  • Forgetting to call the emit function inside event handlers means no event is sent.
vue
<script setup>
// Wrong: no defineEmits used
function handleClick() {
  emit('click') // emit is undefined, error
}

// Correct:
const emit = defineEmits(['click'])
function handleClick() {
  emit('click')
}
</script>
📊

Quick Reference

Tips for using emits in script setup:

  • Always declare emits with defineEmits for type safety and warnings.
  • Use an array for simple event names or an object for validation.
  • Call the returned emit function to send events.
  • Match event names exactly between child and parent.

Key Takeaways

Use defineEmits inside script setup to declare events your component can emit.
The defineEmits function returns an emit function to trigger events.
Declare emits as an array or object with validators for better safety.
Always match event names exactly between child emit and parent listener.
Forgetting defineEmits or typos cause events not to be caught or errors.