DEV Community 👩‍💻👨‍💻

Caio Vinicius
Caio Vinicius

Posted on

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() {
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
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
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.


Article references:

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!