Vue中如何让$emit传递参数与自定义方法自有参数共存?
Hey there! The issue here is how you’re binding the event handler. When you write @customEvent="method1(arg2)", you’re immediately invoking method1 with arg2 when the component renders—not setting it up to listen for the emitted event and pass both values. Here’s how to fix it:
Solution 1: Use an Arrow Function
Wrap your method call in an arrow function to capture the emitted arg1 and pass it along with your arg2:
<component @customEvent="(emittedArg1) => method1(arg2, emittedArg1)"></component>
Your existing method code will work as-is:
method1(arg2, arg1) { console.log("This is the arg2: " + arg2); console.log("This is the arg1: " + arg1); }
Solution 2: Use $event to Access the Emitted Value
Vue provides the special $event variable that represents the value emitted by the child component. You can pass it directly to your method:
<component @customEvent="method1(arg2, $event)"></component>
Your method will receive arg2 first, then the emitted arg1 (via $event):
method1(arg2, arg1) { console.log("This is the arg2: " + arg2); console.log("This is the arg1: " + arg1); }
Either approach will work—pick whichever you find more readable!
内容的提问来源于stack exchange,提问作者yierstem

