What is the alternative to using this.$on method for listening to events in the Vue 3 setup script?

1.2k Views Asked by At

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.

2

There are 2 best solutions below

4
Mussie On

On Vue3, It's pretty straight forward. Function inside setup function can be assigned straight to emit function.

Emit the already defined event from your child component.

<template>
    <input @change="validate" />
</template>

<script setup>
function validate(){
    // Validation
    emit("validate", WithDesiredParameters);
}
const emit = defineEmits(['validate'])
</script>

Then,

ParentComponent.vue

<template>
   <ChildComponent @validate="yourFunction">
</template>

<script setup>
const yourFunction = (event) => {
    // your business logic .. you can access the emitted via event.SomeThing
}
</script>

For more, check out the docs

0
Mises On

Here is an example how you can use emits inside setup function in child component.

ChildComponent.vue

<template>
   <button @click="buttonClick">Click Button</button>
</template>

<script setup>
const emit = defineEmits(['submit'])

function buttonClick() {
  emit('submit') // Works same as $emit('submit') in a template
}
</script>

In composition API, function setup is kind of a life cycle hook that is nearly the same as beforeCreate or created in Vue 2 version.

Link to doc