【问题标题】:Pass parameter while emitting using Vuejs event hub使用 Vuejs 事件中心发出时传递参数
【发布时间】:2019-06-13 03:56:10
【问题描述】:

我已经检查了similar question,但还有一件事我不清楚:

我可以在事件中心的 emit 中传递一个参数,但我需要参数是 VALUE 而不是存储值的 VARIABLE。例如:eventHub.$emit('test_emit', true) 和在 test_emit 上调用的方法应该将其参数设置为 true。

【问题讨论】:

  • 是的,你可以,但你有什么尝试?
  • 正是如此,我试图调用的方法应该只有在通过事件中心调用时才将其参数设置为 true,在所有其他情况下它应该为 false。但是当我将它作为值传递时,我不确定如何获取该参数。在另一边我有eventHub.$on('test_emit', this.functionINeed)

标签: vue.js


【解决方案1】:

根据您提供的类似问题,您只需在发出事件时将 name 替换为 true

methods: {
    showModal(name) { this.bus.$emit('showModal', true); },
}

created() {
    // `show` will have the value that you emitted
    this.bus.$on('showModal', (show) => console.log(show);
}

【讨论】:

  • 那么true 的值会写在show 变量中吗?
  • 还有一点,eventHub.$off 的部分看起来如何?我是否需要在那里包含相同的变量?
  • 不,您只需指定要禁用的事件名称。 documentation for $off。所以this.bus.$off('showModal')就够了
  • 因为您可以为同一事件添加多个侦听器,this.bus.$off('showModal') 将删除所有showModal 事件的侦听器
【解决方案2】:

当然可以,但不能传递多个变量(如eventHub.$emit('test_emit', true, false),因为 $emit 只接受一个附加参数(可以是值或包含键的对象:值关联,也称为有效载荷

【讨论】:

  • 好的,你如何在另一边得到它,你有eventHub.$on
  • eventHub.$on('test_emit', theValue => ...); 或者如果你提供一个函数,函数的第一个参数将是值本身,例如:eventHub.$on('test_emit', anyFn); anyFn = function(value) { console.log(value) }
猜你喜欢
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2018-02-05
  • 2019-09-22
  • 2023-03-09
  • 2017-02-03
  • 2012-06-01
相关资源
最近更新 更多