0

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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're a genius. Thank you!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.