[Vuejs]-Broadcasting event from parent to child fires all parent's children in Vue.js

1👍

$broadcast is used to send event to child components. In your parent component you’re triggering the event loadTasks from the toggle method. This is good.

You’re sending a parameter along in the event, in your case id_epic

Now in your child component, you will need something like this. You need to get the id you’re sending in your child component.

events : {
    'loadTask' : function(param) {
               //check for the id_epic here
     }
 }

EDIT: The parent and it’s children are generated recursively, so the child can also be a parent on it’s own.(Like a folder structure)

You should also re-think that part, if you have too many nested components, things can get easily out of hand.

1👍

You should be able to stop the propagation of an event by using a second parameter in the child listener. The second parameter is passed the event object to which you can can call stopProgation() and prevent additional children from also receiving the broadcasted event.

Consider adding the following code to your child listener.

events:{
    'loadTask': function(param,event){
        event.stopPropagtion();
        // Handle the param as needed.
    }
}

Of course this system of event handling is only for Vue.js 1.0 as in Vue.js 2.0+ event broadcasting and dispatching has been depreciated in favor of a data store such as Vuex. So you may want to consider using a method which will upgrade compatible.

👤Azeame

0👍

You can try using this.$children[0].$emit() to send the event to the first child instance. though it would probably be better to use a more explicit scheme and have children register handlers with the parent or vice versa.

Leave a comment