Suppose we have a child component which emits a custom event iterated
. Is there a way to listen to the event in the parent component via this.$ref
? Like this.$refs.on('iterated', event)
. I know I can listen on component via v-on
or by using watch
, but the documentation says nothing about achieving this on component instance. A simple usecase for this could be an image cropper that emits an event when the cropping is done, to queue the files for multi upload.
Please see the simplified example below.
Child Component
<template>
<p>Count: {{ count }} </p>
<template>
<script>
export default {
data: () => ({
count: 1
}),
mounted () {
const that = this;
setTimeout(() => {
that.count++;
that.$emit('iterated', that.count);
}, 2000);
}
};
</script>
Parent Component
<template>
<child-component ref="myChild" />
<template>
<script>
export default {
mounted () {
this.$refs.myChild.on('iterated', (count) => {
console.log(count);
});
}
};
<script>
// EDIT: This question might be a duplicate (although there is no answer): VueJS 3 : Add event listener through js code