[Vuejs]-Multiple functions on click prevents function with event parameter – Vue

2👍

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.

1👍

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.

Leave a comment