Djave
Djave

Reputation: 9329

Vue broadcast event to multiple components

I have a fairly simple component based question.

If I had 5 components and I click open on one, how can I tell the other 4 that they need to be closed?

To begin with I have put

this.$emit('open');

on the component. Then on the app I have put

@open="closeOthers"

Then in the app I have the following:

'methods':{
  closeOthers : function($event){
    console.log($event);
  }
}

But I'm just logging undefined. How can I

  1. make this not log undefined
  2. update the props on all other components

Full code and demo here >>>

Upvotes: 0

Views: 3279

Answers (1)

Kirill Matrosov
Kirill Matrosov

Reputation: 6000

for 1st. You should pass event throw functions. Like this

   'toggleSelect' : function(e){
      this.$emit('open', e);
      this.question.open = !this.question.open;
    },

after this. This code will work

'methods':{
  closeOthers : function($event){
    console.log($event);
  }
}

for 2nd. To control open state it is better to move open value to parent and pass it to child. Full code jsfiddle

Upvotes: 1

Related Questions