Skip to content Skip to sidebar Skip to footer

Parentheses While Calling A Method In Vue

In Vue, why can you assign a listener both with () and without ()? In the above code snippet, input event on both the input fields trigger changeName nicely in spite one has paren

Solution 1:

This is explained pretty well in https://vuejs.org/v2/guide/events.html#Method-Event-Handlers.

Basically, the event handler can be either

  • a method name, such as @input="changeName"
  • a valid Javascript statement, such as @input="changeName()" or @input="userName = 'Name '+Math.random()"

Vue performs checking automatically to detect which case it is.

If you interested, checkout out this core codes at https://github.com/vuejs/vue/blob/19552a82a636910f4595937141557305ab5d434e/dist/vue.js#L10086 .

var handlerCode = isMethodPath
  ? ("return " + (handler.value) + "($event)")
  : isFunctionExpression
    ? ("return (" + (handler.value) + ")($event)")
    : handler.value;

Solution 2:

That's true that both cases are valid in Vue. But there are some differences.

Quoting: https://forum.vuejs.org/t/difference-when-calling-a-method-function-with-or-without-brackets/41764/4

@input="changeName"

The event object gets passed to the event handler as the first argument when binding only the method name as the event handler.

@input="changeName()"

Alternatively, an actual method call can be used as an event handler. This allows you to pass any custom arguments to the method.


Post a Comment for "Parentheses While Calling A Method In Vue"