DEV Community

cn-2k
cn-2k

Posted on

9 2 1 1 1

Working with emits in Vue 3 + Typescript

In this post I will show you'll how to work with emits Vue 3 + Composition API using <script setup>, there's few ways to work with it, let's take a look!

Using the defineEmits() macro we can declare emits like:

1 - Array of strings

<script setup>
const emit = defineEmits(['inFocus', 'submit'])

function buttonClick() {
  emit('submit')
}
</script>
Enter fullscreen mode Exit fullscreen mode

2 - Object syntax

<script setup>
const emit = defineEmits({
  submit(payload) {
    // return `true` or `false` to indicate
    // validation pass / fail
  }
})
</script>
Enter fullscreen mode Exit fullscreen mode

3 - Runtime or base type declaration

<script setup lang="ts">
// runtime
const emit = defineEmits(['change', 'update'])

// type-based (TS)
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()
</script>
Enter fullscreen mode Exit fullscreen mode

That's it!

If you want to read and learn more details about component emits declaration, please make sure to visit the Vue 3 official documentation about emits.

See'ya!


Article references:
https://vuejs.org/guide/components/events.html
https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (2)

Collapse
 
daxtersky profile image
Miko • Edited

Hey there,

Since version 3.3+ type definition for emits is even more clean:

const emit = defineEmits<{
  'change': [id: number]
  'update': [value: string]
}>()
</script>

Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay