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
v-onis how you add handlers to emitted events from child components:For defining events when using render functions, see the examples in documentation.
Note: under the hood, all event listeners defined as component-emitted events are Custom Events, with the default value for
bubbles, which isfalse.Documentation: Emitting and Listening to Events:
In short, they are only triggered on the child component, and they do not bubble to the parent or subsequent DOM ancestors.