22

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/vue@2.5.16/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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
void
  • 36,090
  • 8
  • 62
  • 107
  • I found another diff between the two and I asked the question here : https://stackoverflow.com/questions/75939333/parentheses-while-calling-a-method-in-vue-changes-the-value-of-this – walox Apr 05 '23 at 12:19

2 Answers2

26

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;
tony19
  • 125,647
  • 18
  • 229
  • 307
Jacob Goh
  • 19,800
  • 5
  • 53
  • 73
10

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.

Dvdgld
  • 1,984
  • 2
  • 15
  • 41