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.