Is there a way to capture events emitted by multiple child components in vuejs?

Viewed 4237

I have a parent component which has multiple child components

<grid>
   <cell></cell>
   <cell></cell>
   <cell></cell>
</grid>

My cell components emit an event with payload saying it is being edited this.$emit('editing',cellId)

I know I can capture the event like <cell @editing="do something"></cell> or capture using EventBus.$on('editing'), I do not want to use root listener as well this.$root.$on('editing')

But because its the parent component, how can i listen to event of 'editing' when the parent component is mounted

mounted: function(){
    this.$on('editing',dosomething)
}

why am I not able to add listen when the parent component is mounted?

3 Answers

TL;DR Stumbled across this issue my self. Like the other said, when you want to bind an event listener from a parent, you need to use v-on because, well ... , you are binding something tot he child. So the actual callback is ran by the child, when that child detects that the event ocured.

In the child use this.$parent.$emit('event-name');
In the parent use

mounted: function() {
    this.$on('event-name', function() {console.log('test')});
}  

The above will let you trigger the event in the parent so you can use $on in the parent to lsiten to that event that was triggered by the child.

Related