Event and Key Modifiers
Shelf's search is a small form. Press Enter and the browser reloads the page, wiping your results. You could write event.preventDefault() at the top of every handler and check event.key === 'Escape' in others. Vue offers a tidier way: little suffixes on v-on that do the chores before your code runs.
The rule
A dot suffix does the chore; your handler keeps only the logic.
Event modifiers handle common event plumbing:
| Modifier | Effect |
|---|---|
.prevent |
calls event.preventDefault() |
.stop |
calls event.stopPropagation(), so parents do not hear it |
.self |
runs only if the event started on this element, not a child |
.once |
runs at most once |
.capture |
listens in the capture phase |
.passive |
tells the browser the handler will not prevent the default, good for scroll |
Key modifiers filter keyboard events by key: .enter, .esc, .space, .tab, .delete, .up, .down, .left, .right. System modifiers require a key to be held: .ctrl, .alt, .shift, .meta, and .exact means "these and no others". Mouse buttons have .left, .right and .middle.
<form @submit.prevent="search">
<input v-model="query"
@keyup.esc="query = ''"
@keydown.ctrl.enter="searchEverywhere" />
</form>
<div class="modal-backdrop" @click.self="closeModal">
<div class="modal">...</div>
</div>
<a href="/books/1" @click.stop.prevent="openPreview(1)">Dune</a>- Enter in the input submits the form;
.preventstops the reload, andsearchruns. - Escape clears the box, without any
ifin the handler. - Ctrl + Enter runs a wider search.
- Clicking the dark backdrop closes the modal, but clicks inside the modal do not, because their target is a child.
Modifiers chain, and order matters: they are applied left to right. @click.prevent.self prevents the default for clicks on the element and its children, while @click.self.prevent prevents it only for clicks on the element itself. Also, do not combine .passive with .prevent; passive promises you will not prevent the default, so the browser ignores the attempt.
The shortcut
When a handler starts with plumbing, turn the first line into a modifier. event.preventDefault() → .prevent. if (event.key !== 'Escape') return → .esc. if (event.target !== event.currentTarget) return → .self.
Before
function search(e) { e.preventDefault(); runSearch(query.value) }on@submit.
Drills
Answer fast — trust the rule.
Which modifier stops a form submission from reloading the page?
What does @keyup.enter="save" do?
A backdrop has @click.self="close". The user clicks a button inside the modal on top of it. Does close run?
A button inside a clickable card should not trigger the card's handler. Which modifier goes on the button's click?
Which pair should never be combined?
Remember
- Event modifiers (
.prevent,.stop,.self,.once) and key modifiers (.enter,.esc,.ctrl) handle plumbing in the template. - Shortcut: plumbing on a handler's first line becomes a modifier.
- Trap: modifier order changes meaning;
.passivewith.preventdoes not work.
