samo
samo
NNuxt
Created by samo on 12/4/2024 in #❓・help
Default emit definition
Hey I'm new to the vue/nuxt ecosystem. One thing I'm confused about is how to properly define a default emit. For example:
<script setup lang="ts">
const app = useNuxtApp()

type Emit = {
(event: 'error', error: Error): void,
(event: 'success', user: User): void
}

const emit = defineEmits<Emit>()
<script setup lang="ts">
const app = useNuxtApp()

type Emit = {
(event: 'error', error: Error): void,
(event: 'success', user: User): void
}

const emit = defineEmits<Emit>()
Now this works and is typed correctly, however if I try to do something akin to withDefaults on props i.e.
const emit = withDefaults(defineEmits<Emit>(), {
error: (error: Errror) => app.$toast.error(error.message),
success: (user: User) => app.$toast.sucess(`Welcome $[user.name}!`)
})
const emit = withDefaults(defineEmits<Emit>(), {
error: (error: Errror) => app.$toast.error(error.message),
success: (user: User) => app.$toast.sucess(`Welcome $[user.name}!`)
})
I've scoured all the vue/nuxt docs and stackoverflow and I was unable to find any reference to this. Is there truly no way to have a default emit handler? If not, what is the best way to do this? I could technically just pass the function in defineProps with a function - issue with this is, I get a hydration warning about mismatch - presumably because of the useNuxtApp composable or props passing / initialization. Thanks in advance
5 replies