v-on — Inline and Method Handlers
Every button on Shelf has to do something: add a page to your progress, mark a book read, remove it. v-on connects a DOM event to your code. It has two forms, and knowing which one you wrote tells you exactly what arguments your function receives.
The rule
Name a function and Vue passes the event; write a call and you pass the arguments.
v-on:click is almost always written @click. The value can be a method handler or an inline handler:
<script setup>
import { ref } from 'vue'
const pagesRead = ref(0)
function addPage(event) {
pagesRead.value++
console.log('clicked at', event.clientX)
}
function markRead(id, event) {
console.log('mark', id, 'from', event?.target.tagName)
}
</script>
<template>
<!-- inline statement -->
<button @click="pagesRead++">+1</button>
<!-- method handler: Vue calls addPage(event) -->
<button @click="addPage">+1 and log</button>
<!-- inline call with an argument -->
<button @click="markRead(7)">Mark read</button>
<!-- inline call passing the native event too -->
<button @click="markRead(7, $event)">Mark read</button>
</template>How Vue decides:
- If the value is just a function name or path, like
addPageoractions.add, it is a method handler. Vue calls the function and passes the native DOM event as the first argument. - Anything else, such as
pagesRead++ormarkRead(7), is an inline handler: a statement Vue runs when the event fires. Nothing is passed automatically. If you need the event, pass the special variable$event, or write an arrow function:@click="(e) => markRead(7, e)".
Inline handlers are handy for one-liners and for passing extra data, such as the id of the book in a v-for. When the logic grows beyond a line, move it into a named function.
v-on works on any DOM event (@input, @submit, @mouseenter) and on component events, as you saw with @remove.
The shortcut
Look at the handler text and ask: "Are there parentheses?" No parentheses → Vue passes the event for you. Parentheses → you pass everything yourself, using $event if you need the event.
The need
Each card's button must tell
removeBookwhich book to remove.
Drills
Answer fast — trust the rule.
With @click="addPage", what does addPage receive as its first argument?
With @click="markRead(7)", what does markRead receive?
How do you pass both a book id and the native event in an inline handler?
What is @submit short for?
Remember
@eventis short forv-on:event; the value is a method name or an inline statement.- Shortcut: no parentheses → Vue passes the event; parentheses → you pass the arguments,
$eventincluded. - Trap:
@click="removeBook"in a loop receives the event, not the book.
