void
void

Reputation: 36703

Parentheses while calling a method in Vue

In Vue, why can you assign a listener both with () and without ()?

new Vue({
  el: "#app",
  data: {
    userName: "Hello World!"
  },
  methods: {
    changeName: function(e){
      this.userName = "Name "+Math.random();
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="app">
  <p> {{ userName }} </p>
  
  <!-- typing in both the input fields trigger changeName  -->
  
  <input @input="changeName()">
  <input @input="changeName">
  
</div>

In the above code snippet, input event on both the input fields trigger changeName nicely in spite one has parentheses around it () and one doesn't.

Upvotes: 23

Views: 6204

Answers (2)

Jacob Goh
Jacob Goh

Reputation: 20855

This is explained pretty well in https://v2.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;

Upvotes: 28

Dvdgld
Dvdgld

Reputation: 2164

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.

Upvotes: 11

Related Questions