Methods & Event Handling
Methods are functions defined on a component, and v-on (almost always written as its @ shorthand) is how a template wires a DOM event, like a click, to one of them.
Defining and calling a method
Methods live in a methods object alongside data(), and inside a method, this refers to the component instance — so this.count reads or writes the same count the template displays:
Vue.createApp({
data() {
return { count: 0 }
},
methods: {
increment() {
this.count++
}
}
})
<p>Count: {{ count }}</p>
<button @click="increment">+1</button>
Count: 0 (initial) Count: 1 (after one click) Count: 2 (after two clicks)
Each click calls increment(), which mutates this.count directly — no setState-style call is needed, because Vue's reactivity system is already watching that property (more on exactly how in the next lesson).
Passing arguments and accessing the event object
You can call a method with your own arguments, and still get access to the native DOM event by passing the special $event variable:
<button @click="removeItem(item.id, $event)">Remove</button>
methods: {
removeItem(id, event) {
console.log('Removing item', id)
event.target.disabled = true
}
}
Event modifiers
Vue provides shorthand modifiers for common patterns that would otherwise need extra code inside the handler, like calling preventDefault():
<form @submit.prevent="handleSubmit"> ... </form>
.prevent automatically calls event.preventDefault() before running handleSubmit, so the form's default full-page submit never happens. Other common modifiers include .stop (stops event propagation) and .once (the handler only fires the first time).
@click too, like @click="count++" — but as soon as the logic is more than a one-liner, pulling it into a named method (as above) keeps the template readable and makes the logic easier to test on its own.