【问题标题】:Vue broadcast event to multiple componentsVue 向多个组件广播事件
【发布时间】:2017-05-30 11:31:09
【问题描述】:

我有一个相当简单的基于组件的问题。

如果我有 5 个组件并且我单击打开其中一个,我如何告诉其他 4 个它们需要关闭?

首先我已经放了

this.$emit('open');

组件上。然后在 app 我放了

@open="closeOthers"

然后在 app 我有以下内容:

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

但我只是记录undefined。我该怎么做

  1. 不记录undefined
  2. 更新所有其他组件的道具

Full code and demo here >>>

【问题讨论】:

  • 您可以使用事件总线:vuejs.org/v2/guide/…
  • 哦...我认为实际上这可能有点矫枉过正,我可以去this.$emit('open', this.question.id); 然后在我的应用程序中去寻找每个问题,如果它的 id 不是问题id,隐藏它。
  • 如果您的“多个组件”具有相同的父级,那么您是对的。

标签: vue.js vuejs2


【解决方案1】:

第一名。您应该传递事件抛出函数。像这样

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

之后。此代码将起作用

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

第二名。要控制打开状态,最好将打开值移动到父级并将其传递给子级。 Full code jsfiddle

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 2019-05-16
    • 2016-04-20
    • 1970-01-01
    • 2019-05-05
    • 2016-01-25
    • 2016-06-12
    相关资源
    最近更新 更多