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)
}
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)
}
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.
<div @click="test"></div>
Result:: ~502,653 operations per second.
<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.
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)
},