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>
2 - Object syntax
<script setup>
const emit = defineEmits({
submit(payload) {
// return `true` or `false` to indicate
// validation pass / fail
}
})
</script>
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>
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
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.