2

Is it better practice to pass in the event when using it in a method or to just have it implied:

option1:

<input @keyup.enter="chooseMe($event)"/>

option2:

<input @keyup.enter="chooseMe"/>

chooseMe(evt) {
    console.log(evt)
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
HayleeGal58
  • 225
  • 3
  • 8

2 Answers2

1

I'll assume that you are asking about performance rather than developer opinion. (For example, it could be argued that explicitly passing the $event argument makes the component's intention clearer, but that's an opinion. It's also more verbose.)

The compiler generates a wrapper function around any handler that uses a function invocation (i.e. () in the attribute value), to allow for passing $event as an argument. When using modifiers like .enter in your example, it does this even if there is no invocation.

To test any performance impact, you can use a test suite like JSBench.me. Here are the results of such a test running on Windows/Chrome.

  1. Implicit
<div @click="test"></div>

Result:: ~502,653 operations per second.

  1. Explicit
<div @click="test($event)"></div>

Result:: ~536,685 operations per second.

It's faster (by an imperceptible margin) to include the $event in this case. But the difference is insignificant enough to be irrelevant. If you had to compile 500,000 event handlers, the act of compilation for both syntaxes would take around 1 second.

Dan
  • 59,490
  • 13
  • 101
  • 110
  • Don't feel bad that the question got closed, it's a good question. They misunderstood that you weren't asking about stylistic opinion, but performance and/or factual differences. – Dan Feb 28 '21 at 21:03
0

In Option1 you create an expression each time the component gets rendered. But, in Option2 in each cycle, just one method is addressed. So, it's better to define methods and address them in the template.

Consider this sample:

<list>
  <li
      v-for="item in items" :key="item.id"
      @click="theClickHandler(item)"
  ></li>
</list>

There are a theClickHandler method and item.length different expressions in each render (at most)!!

To handle this situation you can use HTML data attributes:

<list>
  <li
      v-for="item in items" :key="item.id"
      :data-id="item.id"
      @click="theClickHandler"
  ></li>
</list>

and get the clicked item in hanlder method:

theClickHandler(e) {
  const id = e.target.dataset.id
  const [item] = this.items.filter(x => x.id === id)
  console.log('clicked item:', item)
},
Raeisi
  • 1,647
  • 1
  • 6
  • 18