4 min read
•Question 8 of 37easyHow do Custom Events work in Vue?
Emitting events from child to parent.
What You'll Learn
- Emitting events
- Event arguments
- v-model with events
Emitting Events
code.txtVUE
<!-- ChildComponent.vue -->
<script setup>
const emit = defineEmits(['increment', 'submit'])
function handleClick() {
emit('increment')
}
function handleSubmit(data) {
emit('submit', data)
}
</script>
<template>
<button @click="handleClick">Increment</button>
<button @click="handleSubmit({ name: 'Vue' })">Submit</button>
</template>Listening to Events
code.txtVUE
<!-- ParentComponent.vue -->
<template>
<ChildComponent
@increment="count++"
@submit="handleSubmit"
/>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function handleSubmit(data) {
console.log(data) // { name: 'Vue' }
}
</script>TypeScript Events
code.txtVUE
<script setup lang="ts">
const emit = defineEmits<{
(e: 'increment'): void
(e: 'submit', data: { name: string }): void
}>()
</script>