Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue,how to listen to same event from two child components inside parent?

<template id="parentComp">
<child-comp-1 @customEvent="handler"/>
<child-comp-2 @customEvent="handler"/>
</template>

Since I receive the same event and use the same event handler for both events , is there a way to listen to them in common , ie can I make the event bubble up like native events and use something like

 <template id="parentComp" @customEvent="handler">
like image 527
Sainath S.R Avatar asked Jan 18 '26 15:01

Sainath S.R


2 Answers

Other than just passing the event to the parent you can use an event bus. This article describes this principle well: https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

The idea is to use a shared Vue instance to handle events. You will then import this instance in different elements, the same way you would import a library.

like image 183
Raphaël Verdier Avatar answered Jan 21 '26 07:01

Raphaël Verdier


To listen from multiple components. Emit and listen the event from root level

this.$root.$emit('myTestEvent',dataToBeSent);

Now you can listen from any component using

mounted(){
    this.$root.$on('myTestEvent', (dataReceived) => {
       //...
    })
}
like image 34
Afraz Ahmad Avatar answered Jan 21 '26 06:01

Afraz Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!