Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue component is not passing events through

Tags:

vue.js

vuejs2

I have three nested components

<parent @event="handle">
  <inbetween @event="$emit('event')">
    <child> // emits event
    </child>
  </inbetween>
</parent>

so, when a child emits the event, I have to add that annoying part @event="$emit('event')" to the component inbetween, otherwise parent does not receive any event.

I hope it is not supposed to work that way. I wonder what could be wrong with it?

like image 999
igor Avatar asked Mar 07 '23 13:03

igor


2 Answers

Yes thats how its supposed to work. Events go only from child to parent, it does not go from child up to grand parent. Therefore you have to emit the event from both child and inbetween component.

If you want to avoid this method you can use Event Bus:

https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

alligator.io/vuejs/global-event-bus

like image 74
Omar Tanti Avatar answered Mar 25 '23 09:03

Omar Tanti


This is actually intentional. The reasoning is, when looking at the code for one component and you see that it's listening to an event, you can then look at the template to see where that event is coming from. If events could reach a component arbitrarily deep, it would be harder to figure out how and from where that event is being triggered.

However, Vue used to have a way of doing what you want to do, through the methods $broadcast and $dispatch, and they were eventually removed for the reasons talked about here. Here's a page from the docs which explains why, along with possible solutions, such as using a global event bus, or a centralized state management solution such as Vuex.

like image 25
kingdaro Avatar answered Mar 25 '23 09:03

kingdaro