Asked By: Anonymous
In Vue, why can you assign a listener both with ()
and without ()
?
new Vue({_x000D_
el: "#app",_x000D_
data: {_x000D_
userName: "Hello World!"_x000D_
},_x000D_
methods: {_x000D_
changeName: function(e){_x000D_
this.userName = "Name "+Math.random();_x000D_
}_x000D_
}_x000D_
})
_x000D_
<a href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js</a>_x000D_
_x000D_
<div id="app">_x000D_
<p> {{ userName }} </p>_x000D_
_x000D_
<!-- typing in both the input fields trigger changeName -->_x000D_
_x000D_
<input @input="changeName()">_x000D_
<input @input="changeName">_x000D_
_x000D_
</div>
_x000D_
_x000D_
x000D
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.
Solution
Answered By: Anonymous
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;