Performance: v-on directive for events
This affects how quickly the page responds to user interactions and how efficiently event listeners are managed in the browser.
<template> <ul v-on: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 id = event.target.dataset.id; if (id) console.log('Clicked', id); } </script>
<template>
<ul>
<li v-for="item in items" :key="item.id" v-on:click="handleClick(item.id)">{{ item.name }}</li>
</ul>
</template>
<script setup>
const items = Array(1000).fill(0).map((_, i) => ({ id: i, name: `Item ${i}` }));
function handleClick(id) {
console.log('Clicked', id);
}
</script>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Individual v-on on many elements | Many listeners attached | 0 (no layout changes) | Low paint cost | [X] Bad |
| Single v-on on parent with delegation | One listener attached | 0 (no layout changes) | Low paint cost | [OK] Good |
v-on directive do in Vue?v-onv-on is used to listen to user actions like clicks or key presses.v-on runs the specified code or method.v-on?v-on syntaxv-on followed by the event name, like v-on:click.handleClick is correct.<button v-on:click="count++">Clicked {{ count }} times</button>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>countcount is a reactive reference starting at 0, so changes update the UI automatically.count++, increasing the value by 1 and updating the displayed text.<button v-on:click="submitForm()">Submit</button>
<script setup>
function submitForm {
alert('Form submitted')
}
</script>submitForm is declared without parentheses, which is invalid syntax in JavaScript.function submitForm() { ... } with parentheses after the name.v-on and run a method only when the Enter key is pressed. Which is the correct way to do this in Vue?.enter to listen only for Enter key presses.v-on:keyup.enter="submit()" listens for keyup events only when Enter is pressed and runs submit().Pass the test and this pattern moves unknown