Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
void Avatar asked Jun 01 '18 02:06

void


People also ask

How do you define a method in Vue?

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.

What is $listeners in Vue?

$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.

How do you call a method on page load Vue?

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.


1 Answers

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;
like image 85
Jacob Goh Avatar answered Oct 22 '22 09:10

Jacob Goh