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.
We can define methods on a Vue instance by passing an object to the methods property. Vue methods are similar to JavaScript functions and allow us to add interactivity to our Vue apps.
$listeners is used for passing the event to be invoked in a child component. As similar to $listeners, Setting v-bind="$attrs" in a parent component with props can be also used for passing data. Both id and name props are passed to inherited-child from the parent component.
We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.
This is explained pretty well in https://vuejs.org/v2/guide/events.html#Method-Event-Handlers.
Basically, the event handler can be either
@input="changeName"
@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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With