【问题标题】:Vue $emit passing argument to a function that already have argumentsVue $emit 将参数传递给已经有参数的函数
【发布时间】:2018-04-09 09:12:51
【问题描述】:

我的组件中有这个:

template: <input @blur="$emit('customEvent', arg1)" v-model="arg1">

这在我的 html 模板中:

<component @customEvent="method1(arg2)"></component>

我需要为method1() 函数提供一个参数(arg2),但我还需要从$emit() 获取arg1

我试过这个(进入 Vue 实例):

method1(arg2, arg1) {
      console.log("This is the arg2: " + arg2);
      console.log("This is the arg1: " + arg1);
    }

当然,我试图扭转它们,但不起作用,arg1 没有被通过,而是被替换了。

我知道它必须有一个命名空间(可能类似于arg1=arg1),但我还没有找到类似的东西。

【问题讨论】:

  • 这是否是父子组件通信。
  • 我想知道这是否可行。

标签: javascript vue.js vuejs2


【解决方案1】:

它可以通过将$event 传递给方法来工作。

$event 将是您在 emit 函数中传递的有效负载。当您执行$emit('customEvent', arg1) 时,arg1 将作为$event 传递给@customEvent。

<component @customEvent="method1($event, arg2)"></component>

在方法中:

method1(arg1, arg2) {
  console.log("This is the arg2: " + arg2);
  console.log("This is the arg1: " + arg1);
}

概念证明:https://jsfiddle.net/jacobgoh101/e8a5k3ph/1/


替代解决方案:

<component @customEvent="(eventPayload) => method1(eventPayload, arg2)"></component>

【讨论】:

  • 效果很好,我一直在寻找这个解决方案很长一段时间.. 但老实说,这真的看起来像一个 hack :/
  • @Dany 感觉不像黑客的另一种选择是将函数传递给事件处理程序。 @customEvent="(eventPayload) =&gt; method1(eventPayload, arg2)"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 2021-04-13
  • 2022-01-01
  • 2021-04-18
相关资源
最近更新 更多