I used Vue a few years ago, but haven't written any code since the composition API was released. I'm having trouble finding documentation on how to listen to events within a component using the new <script setup>. In my component, I have an event called 'validate', which I've registered using defineEmits. In the past, I would have listened for this event in the mounted hook using this.$on. What is the alternative approach to doing this in the Vue 3 <script setup>?
This is how I defined the event
<template>
<input @change="validate" />
</template>
<script setup>
function validate(){
// Validation
}
const emit = defineEmits(['validate'])
</script>
Vue 2 version of what I'm trying to achieve
<template>
<input @change="validate" />
</template>
<script>
export default {
methods: {
validate(){
//validation
}
},
mounted(){
this.$on('validate', validate)
}
}
</script>
Please correct me if I'm following the wrong idea here. I haven't been following the updates for a while. I'd really appreciate any useful hints.
Thanks in advance.
On Vue3, It's pretty straight forward. Function inside
setupfunction can be assigned straight toemitfunction.Emit the already defined event from your child component.
Then,
ParentComponent.vue
For more, check out the docs