Dan Knights
Dan Knights

Reputation: 8368

Multiple functions on click prevents function with event parameter - Vue

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

Answers (2)

skirtle
skirtle

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:

https://github.com/vuejs/vue/blob/0baa129d4cad44cf1847b0eaf07e95d4c71ab494/src/compiler/codegen/events.js#L96

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

Sebastian Speitel
Sebastian Speitel

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

Related Questions