我的组件中有这个:
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/