Performance: Passing arguments to handlers
This affects interaction responsiveness and rendering speed when event handlers receive arguments in Vue components.
<button @click="handleClick" :data-id="item.id">Click</button> // In script function handleClick(event) { const id = event.currentTarget.dataset.id; // handle click with id }
<button @click="() => handleClick(item.id)">Click</button>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline arrow function in template | No extra DOM nodes | 0 | Low | [X] Bad |
| Stable handler with data attributes | No extra DOM nodes | 0 | Low | [OK] Good |
42 to a click event handler named handleClick in the template?@click to bind click events and parentheses to pass arguments.@click="handleClick(42)" calls handleClick with argument 42 on click.'hello' to a method sayHello in Vue template?@click="sayHello('hello')" correctly passes the string 'hello'. Others are invalid syntax.<button @click="increment(5)">Add 5</button>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment(amount) {
count.value += amount
}
</script>count.value after clicking the button twice?count.value is 0. The increment function adds the passed amount to count.value.<button @click="submitForm(formData)">Submit</button>
<script setup>
const formData = { name: 'Alice' }
function submitForm() {
console.log(formData)
}
</script>formData as an argument, but submitForm has no parameters defined.id and the native event object to a Vue method handleClick. Which is the correct way to do this in the template?$event for native event$event is Vue's special variable for the native event object.@click="handleClick(id, $event)" correctly passes id first, then the event.Pass the test and this pattern moves unknown