2
<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">
Sainath S.R
  • 3,074
  • 9
  • 41
  • 72

3 Answers3

1

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.

  • An event bus is really here the correct solution, since when your project will grow, it'll still be more manageable than using `$listeners`. Also, if it continue to grow more, you'll be in good shape to switch to Vuex. – Alex May 25 '18 at 18:40
1

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) => {
       //...
    })
}
Afraz Ahmad
  • 5,193
  • 28
  • 38
0

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/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <outer-com @inner-com-click-event="eventHandler"></outer-com>
</div>
jacky
  • 1,426
  • 6
  • 10