Performance: Why event handling matters
Event handling affects how quickly the page responds to user actions and how much work the browser must do during interactions.
<template> <ul @click="handleListClick"> <li v-for="item in items" :key="item.id" :data-id="item.id">{{ item.name }}</li> </ul> </template> <script setup> const items = Array(1000).fill(0).map((_, i) => ({ id: i, name: `Item ${i}` })); function handleListClick(event) { const li = event.target.closest('li'); if (!li) return; const id = Number(li.dataset.id); const item = items.find(i => i.id === id); if (item) console.log(item.name); } </script>
<template>
<ul>
<li v-for="item in items" :key="item.id" @click="handleClick(item)">{{ item.name }}</li>
</ul>
</template>
<script setup>
const items = Array(1000).fill(0).map((_, i) => ({ id: i, name: `Item ${i}` }));
function handleClick(item) {
console.log(item.name);
}
</script>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Individual listeners on many elements | Many listeners attached | 0 | 0 | [X] Bad |
| Single delegated listener on parent | One listener attached | 0 | 0 | [OK] Good |
@event shorthand or v-on:event to listen for events.@click, the recommended shorthand for click events in Vue templates.export default {
methods: {
sayHi() {
alert('Hi!')
}
}
}
<template>
<button @click="sayHi">Greet</button>
</template>
sayHi shows an alert with 'Hi!'. The button listens for click and calls this method.sayHi, so an alert box with 'Hi!' appears.<template>
<button @click="submitForm">Submit</button>
</template>
<script>
export default {
methods: {
submitform() {
console.log('Form submitted')
}
}
}
</script>
submitForm but the method is named submitform (lowercase f), causing a mismatch.<template>
<input @input="updateMessage" />
<p>Message: {{ message }}</p>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
function updateMessage(event) {
// What should go here?
}
</script>
message is a ref, so to update its value, use message.value. The event object has the input value in event.target.value.message.value = event.target.value updates the reactive ref correctly.Pass the test and this pattern moves unknown