Performance: Method handlers vs inline handlers
This affects how Vue processes event listeners and updates the DOM, impacting interaction responsiveness and rendering speed.
<template> <button @click="doSomething">Click me</button> </template> <script setup> function doSomething() { console.log('Clicked') } </script>
<template> <button @click="() => doSomething()">Click me</button> </template> <script setup> function doSomething() { console.log('Clicked') } </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline handler (e.g., @click="() => doSomething()") | Multiple add/remove event listeners per render | 0 (no layout change) | Low paint cost but higher CPU for listener management | [X] Bad |
| Method handler (e.g., @click="doSomething") | Single event listener reused | 0 (no layout change) | Low paint cost and minimal CPU overhead | [OK] Good |
submitForm on a button click in Vue?<template>
<button @click="count++">Increment</button>
<p>Count: {{ count }}</p>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>@click="count++" directly increments the reactive count variable when clicked.count is a ref, Vue tracks changes and updates the displayed value in {{ count }} automatically.<button @click="increment">Add</button>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count++
}
</script>.value property, not directly with count++.count++, which is invalid because count is a ref object, not a number.isActive in your Vue component when a button is clicked. Which approach best balances clarity and simplicity?Pass the test and this pattern moves unknown