Sainath S.R
Sainath S.R

Reputation: 3306

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">

Upvotes: 3

Views: 4776

Answers (3)

Afraz Ahmad
Afraz Ahmad

Reputation: 5386

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) => {
       //...
    })
}

Upvotes: 1

jacky
jacky

Reputation: 1446

you can use $listeners for event bubbling. give you an example

Vue.component('inner-com',{
  template: '<div>inner component<button @click="innerClick">emit event</button></div>',
  methods: {
    innerClick () {
      this.$emit('inner-com-click-event');
    }
  }
})

Vue.component('middle-com',{
  template: '<div>middle component<inner-com v-on="$listeners"></inner-com></div>'
})

Vue.component('outer-com',{
  template: '<div>outer component<middle-com v-on="$listeners"></middle-com></div>'
})


var app = new Vue({
  el:'#app',
  methods: {
    eventHandler () {
      alert('event receved')
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <outer-com @inner-com-click-event="eventHandler"></outer-com>
</div>

Upvotes: 0

Rapha&#235;l Verdier
Rapha&#235;l Verdier

Reputation: 125

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.

Upvotes: 1

Related Questions