1

Please see this minimum example:

<template>
  <div>
    <!-- I understand that this works -->
    <button @click="click">Click</button>
    <!-- Why is this working? Does Vue has some kind of auto detection? -->
    <!-- If so, how does Vue detect it? -->
    <button @click="click()">Click</button>
  </div>
</template>

<script>
export default {
  methods: {
    click() {
      alert("Clicked!");
    }
  }
};
</script>

As you can see, I have a click method that simply alert something, and I have two different way to bind the method in template, why is this happening?

How does Vue resolve @click="click()" under the hood? Why does this not immediately invoke click method once?

Joseph
  • 3,974
  • 7
  • 34
  • 67
  • Which one are you unsure about, click('hello there') or just the click? – Spangle Feb 06 '20 at 05:53
  • `click('hello there')` is the one that I confused about. Because I came from React, and we used to pass function reference all the time. – Joseph Feb 06 '20 at 05:55
  • As for the how, I am unsure sorry, but why, well you can now give an argument to the function like I did in the comment above 'hello there'. – Spangle Feb 06 '20 at 05:56
  • Although it's convenient, that really confuses me, because Vue certain do some kind of auto-detection, I wish to know what's under the hood – Joseph Feb 06 '20 at 05:58
  • 1
    Have a read of this https://stackoverflow.com/questions/50635404/parentheses-while-calling-a-method-in-vue/50635834 – Spangle Feb 06 '20 at 05:59
  • Now I understand, thank you. – Joseph Feb 06 '20 at 06:09
  • 1
    `click()` allows you to pass additional arguments/params into the method, while `click` does not. However, they will both invoke the same method in the Vue component instance, probably because Vue internally checks if the component contains a member `click` whose typeof is a `function`, and internally invokes it as a function. – Terry Feb 06 '20 at 08:19

1 Answers1

2

In both cases click function will be invoked, but The difference is:

@click="click"

For this case, invoking click function and passing parameter will be scope of element on which it is triggered.

Example:

click(event) {
     //here you will receive event object by default
    }

@click="click()"

For this case, allowing you to pass custom parameters to click function.

Example:

click(event) {
     //here you will receive event object is null, because intentionally you did not pass anything
    }
Mahamudul Hasan
  • 2,745
  • 2
  • 17
  • 26