Reputation: 8368
If I have multiple functions passed to a click event i.e.
@click="
inputHandler();
sendToken(computedUser.email);
responseMessage();
"
The function with an event parameter:
inputHandler(e) {
// code
}
Won't run. If I pass it on it's own:
@click="inputHandler"
It works fine.
Why is this and how can I get around it?
Upvotes: 0
Views: 1596
Reputation: 29112
Internally Vue uses some RegExps to decide what form of event handler you're using.
If it seems to be the name of a method it will call it and pass the event.
If it seems to be inline code it'll just run it. In this case the event object is accessible as $event
.
So:
@click="inputHandler($event)"
is roughly equivalent to:
@click="inputHandler"
Strictly speaking these aren't quite the equivalent, for example with component events that emit multiple arguments you'll only get the first one using $event
like this.
See https://v2.vuejs.org/v2/guide/events.html#Methods-in-Inline-Handlers
For a deeper understanding see the Vue source code:
Give your eyes a few minutes to adjust and it isn't too difficult to understand.
Personally I try to avoid anything more complicated than a single method call in the inline listener. Instead I'd suggest having something like @click="onSendClick"
and let the method onSendClick
worry about the details.
Upvotes: 2
Reputation: 7346
If I recall correctly, vue creates a wrapper function, if the passed value isn't a function. So
inputHandler();
sendToken(computedUser.email);
responseMessage();
actually get's turned into
function wrapper(){
inputHandler();
sendToken(computedUser.email);
responseMessage();
}
And as you can see the arguments passed to wrapper are lost. The easiest way to fix this is probably to create a new method that accepts the event parameter and calls all of your function and use that one in the event handler.
Upvotes: 1