javascript - Vue $emit 将参数传递给已经有参数的函数

标签 javascript vue.js vuejs2

我的组件中有这个:

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

这在我的 html 模板中:

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

我需要为 method1() 函数提供一个参数 (arg2),而且我还需要从 $emit()

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

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

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

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

最佳答案

它可以通过将 $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>

关于javascript - Vue $emit 将参数传递给已经有参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49729384/

相关文章:

Javascript函数停止其他函数的工作

javascript - 单击时未调用函数?

javascript - 当值退格时,无法清除其他文本框

webpack - 初始化 vue-cli 时颁发者证书问题

vue.js - 如何使用 Vuex 模块发布 Vue.js NPM 包?

javascript - js 中的 Highchart 在 Vue.js 中不起作用

vue.js - 如何在 Vue.js 中保留自定义组件标签名称

javascript - 考虑半圆计算鼠标位置的百分比

javascript - 通过输入文本过滤 ul 列表 Vue.js 2

vue.js - "You are binding v-model directly to a v-for iteration alias"