Vue.js course · Module 5: Events & Forms
Event Modifiers
In this lesson4
The first test of the Control Simulator ended in a failure. An operator submitted a form with a command, and the browser reloaded the page and wiped the entire simulator state. A moment later the operator clicked a button inside a panel that also reacts to clicks itself, and two procedures ran at once. In plain JavaScript you cure this with calls to event.preventDefault() and event.stopPropagation() at the start of the function. Vue has a shorter notation: modifiers, a dot and a name appended to the event name.
How an event travels through the DOM
To understand modifiers, you need to know how an event travels. A button click goes through three phases. In the capture phase the event descends from the browser window and document down the tree to the clicked element. In the target phase it reaches the button itself. In the bubble phase it goes back up: from the button to the parent <div>, then to <body>, <html> and document. A listener attached with @click works in the bubble phase by default, which is why clicking the button also runs the parent's procedure.
Event Modifiers
.prevent calls event.preventDefault(), which blocks the browser's default action, for example the page reload after a form is submitted. .stop calls event.stopPropagation() and stops the bubbling towards the parents. .once lets the procedure work only on the first event. The first part of the template shows these three modifiers.
<template>
<!-- .prevent - prevents default action -->
<form @submit.prevent="onSubmit">
<button type="submit">Submit</button>
</form>
<!-- .stop - stops propagation -->
<div @click="outer">
<button @click.stop="inner">Only inner</button>
</div>
<!-- .once - only once -->
<button @click.once="runOnce">Only once</button>The form submits without reloading the page and calls onSubmit. Clicking the button inside the <div> prints only inner, because .stop does not let the event out to the parent. The button with .once reacts once, and further clicks pass without a trace. The second part of the template shows the modifiers related to event phases.
<!-- .self - only on this element -->
<div @click.self="onlyThis">
<button>Click on button won't trigger onlyThis</button>
</div>
<!-- .capture - capture mode -->
<div @click.capture="captureFirst">
<button @click="child">Child</button>
</div>
<!-- .passive - for scroll performance -->
<div @scroll.passive="onScroll">Scroll content</div>
<!-- Combinations -->
<a @click.stop.prevent="handleLink">Link</a>
</template>.self runs the procedure only when the event happened on the element itself, not on one of its children. .capture attaches the listener in the capture phase, so captureFirst runs before the child's procedure. .passive tells the browser that the procedure will not block the default action, so scrolling can start right away, without waiting for it. It is most often added to touch and mouse wheel events. Do not combine it with .prevent, because the two contradict each other. Modifiers can be chained, as in @click.stop.prevent, but the order matters: @click.prevent.self blocks the default action for clicks on the children too, while @click.self.prevent blocks it only for clicks on the element itself. Finally, the script with the functions.
<script setup>
function onSubmit() {
console.log('Form submitted without page reload')
}
function outer() { console.log('outer') }
function inner() { console.log('inner') }
function runOnce() { console.log('This runs only once') }
function onlyThis() { console.log('Clicked on div itself') }
</script>The functions are simple, because all the event logic lives in the template, and we left out the remaining procedures, such as captureFirst, for brevity. I recommend this rule: a modifier instead of a manual preventDefault in the function. The procedure stays pure mission logic, and the browser behavior is visible right in the template.
Key Modifiers
With keyboard events, keyup and keydown, a modifier can point to a specific key. Vue has the aliases .enter, .tab, .delete (captures both Delete and Backspace), .esc, .space and the arrows .up, .down, .left and .right. Any name from event.key also works when written in lowercase with dashes, for example .page-down.
<template>
<!-- Specific keys -->
<input @keyup.enter="submit" placeholder="Enter to submit" />
<input @keyup.esc="cancel" placeholder="Esc to cancel" />
<!-- Arrow keys -->
<div tabindex="0" @keyup.up="moveUp" @keyup.down="moveDown"
@keyup.left="moveLeft" @keyup.right="moveRight">Control panel</div>
<!-- Function keys -->
<input @keyup.delete="deleteItem" />
<input @keyup.space="togglePlay" />
<input @keyup.tab="nextField" />The arrow panel has tabindex="0", because a plain <div> does not take focus, and keyboard events go to the focused element. Watch out for @keyup.tab: Tab moves the focus to the next field, so the keyup event already lands there, and you catch leaving a field with @keydown.tab. The system keys .ctrl, .alt, .shift and .meta (Cmd on a Mac, the Windows key on a PC) combine with others into shortcuts.
<!-- Combinations with modifiers -->
<input @keyup.ctrl.enter="submitWithCtrl" />
<input @keyup.shift.delete="forceDelete" />
<input @keyup.alt.s="saveShortcut" />
<input @keyup.meta.s="macSave" /> <!-- Cmd on Mac -->
<!-- Exact modifier -->
<input @keyup.ctrl.exact="onlyCtrl" /> <!-- Only Ctrl, not Ctrl+Shift -->
</template>@keyup.ctrl.enter fires when you release Enter while holding Ctrl, because with keyup the system key has to be pressed at the moment of the event. .exact requires exactly this set of system keys: @keyup.ctrl.exact will not react when you hold Shift together with Ctrl.
Mouse Modifiers
The .left, .right and .middle modifiers restrict the procedure to the main, secondary and auxiliary button. The names assume a right-handed mouse, but they stand for the roles of the buttons, not their physical position.
<template>
<!-- Mouse buttons -->
<div @click.left="leftClick">Left click</div>
<div @click.right="rightClick">Right click</div>
<div @click.middle="middleClick">Middle click</div>
<!-- Context menu -->
<div @contextmenu.prevent="showCustomMenu">
Right click = custom menu
</div>
</template>
<script setup>
function leftClick() { console.log('Left') }
function rightClick() { console.log('Right') }
function middleClick() { console.log('Middle') }
function showCustomMenu(e) {
console.log('Custom menu at:', e.clientX, e.clientY)
}
</script>Browsers send click only for the main button, which is why Vue compiles @click.right to the contextmenu event and @click.middle to mouseup. Hence a practical conclusion: .right on its own will not hide the browser menu. You build your own context menu with @contextmenu.prevent, as in the last element of the example, and e.clientX and e.clientY tell you where to open it. In the next lesson you will move on to forms and the v-model directive.
Remember: a modifier is a filter on the signal line - it lets only the right commands through to the procedure and suppresses the ones the browser would carry out on its own.
Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'
const commandLog = ref([])
const secretCode = ref('')
const mouseAction = ref('')
const addLog = (message) => {
commandLog.value.unshift({
id: Date.now(),
message,
time: new Date().toLocaleTimeString()
})
if (commandLog.value.length > 5) {
commandLog.value.pop()
}
}
const handleEnter = () => {
addLog('⏎ Enter: Command executed!')
if (secretCode.value === 'MARS') {
addLog('Access code accepted!')
}
}
const handleEscape = () => {
addLog('⎋ Escape: Operation cancelled')
secretCode.value = ''
}
const handleDelete = () => {
addLog('⌫ Delete: Data removed')
}
const handleLeftClick = () => {
mouseAction.value = 'Left button: Scanning the left sector'
addLog('Left mouse button')
}
const handleRightClick = (event) => {
event.preventDefault()
mouseAction.value = 'Right button: Scanning the right sector'
addLog('Right mouse button')
}
const handleMiddleClick = () => {
mouseAction.value = 'Middle button: Scanning central sector'
addLog('Middle mouse button')
}
</script>
<template>
<div class="command-center">
<div class="center-header">
<h2>⌨NOVA LAB Command Center</h2>
<p class="subtitle">Key and Mouse Modifiers</p>
</div>
<div class="input-section">
<div class="input-group">
<label>Access code (type MARS and press Enter):</label>
<input
v-model="secretCode"
@keyup.enter="handleEnter"
@keyup.esc="handleEscape"
@keyup.delete="handleDelete"
type="text"
placeholder="Enter code..."
class="command-input"
/>
</div>
<div class="key-hints">
<span class="hint">Enter - Execute</span>
<span class="hint">Esc - Cancel</span>
<span class="hint">Delete - Remove</span>
</div>
</div>
<div class="mouse-section">
<h3>Mouse Scanner Control</h3>
<div class="scanner-area">
<div
class="scan-zone"
@click.left="handleLeftClick"
@click.right="handleRightClick"
@click.middle="handleMiddleClick"
>
<p>Click with different mouse buttons</p>
<p class="action-display">{{ mouseAction || 'Waiting for command...' }}</p>
</div>
</div>
</div>
<div class="log-section">
<h3>Command Log</h3>
<div class="log-container">
<div
v-for="log in commandLog"
:key="log.id"
class="log-entry"
>
<span class="log-time">{{ log.time }}</span>
<span class="log-message">{{ log.message }}</span>
</div>
<div v-if="commandLog.length === 0" class="log-empty">
No activity...
</div>
</div>
</div>
<div class="modifiers-info">
<h3>Available modifiers:</h3>
<div class="modifier-grid">
<div class="modifier-item">
<strong>Keys:</strong>
<code>.enter</code>
<code>.esc</code>
<code>.delete</code>
<code>.tab</code>
<code>.space</code>
</div>
<div class="modifier-item">
<strong>Mouse:</strong>
<code>.left</code>
<code>.right</code>
<code>.middle</code>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.command-center {
background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
color: #00ff88;
padding: 30px;
border-radius: 15px;
border: 2px solid #00b4d8;
font-family: 'Courier New', monospace;
max-width: 900px;
margin: 0 auto;
}
.center-header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #00b4d8;
}
.center-header h2 {
color: #00ff88;
margin: 0 0 10px 0;
font-size: 28px;
text-shadow: 0 0 10px #00ff88;
}
.subtitle {
color: #00b4d8;
margin: 0;
font-size: 14px;
}
.input-section {
margin-bottom: 30px;
}
.input-group {
margin-bottom: 15px;
}
.input-group label {
display: block;
color: #00b4d8;
margin-bottom: 10px;
font-size: 14px;
}
.command-input {
width: 100%;
background: rgba(0, 180, 216, 0.1);
border: 2px solid #00b4d8;
border-radius: 8px;
padding: 15px;
color: #00ff88;
font-size: 16px;
font-family: 'Courier New', monospace;
box-sizing: border-box;
}
.command-input:focus {
outline: none;
border-color: #00ff88;
box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
}
.key-hints {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.hint {
background: rgba(0, 255, 136, 0.1);
border: 1px solid #00ff88;
padding: 5px 12px;
border-radius: 20px;
font-size: 12px;
color: #00ff88;
}
.mouse-section {
margin-bottom: 30px;
}
.mouse-section h3 {
color: #00ff88;
margin-bottom: 15px;
}
.scanner-area {
background: rgba(0, 180, 216, 0.05);
padding: 20px;
border-radius: 8px;
border: 2px dashed #00b4d8;
}
.scan-zone {
background: linear-gradient(135deg, rgba(0, 180, 216, 0.2) 0%, rgba(0, 255, 136, 0.1) 100%);
padding: 40px;
border-radius: 8px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
}
.scan-zone:hover {
background: linear-gradient(135deg, rgba(0, 180, 216, 0.3) 0%, rgba(0, 255, 136, 0.2) 100%);
transform: scale(1.02);
}
.scan-zone p {
margin: 0 0 10px 0;
color: #00b4d8;
}
.action-display {
color: #00ff88 !important;
font-weight: bold;
font-size: 18px;
}
.log-section {
margin-bottom: 30px;
}
.log-section h3 {
color: #00ff88;
margin-bottom: 15px;
}
.log-container {
background: rgba(0, 0, 0, 0.3);
border: 1px solid #00b4d8;
border-radius: 8px;
padding: 15px;
max-height: 200px;
overflow-y: auto;
}
.log-entry {
padding: 8px;
margin-bottom: 5px;
background: rgba(0, 180, 216, 0.1);
border-radius: 4px;
display: flex;
gap: 15px;
}
.log-time {
color: #00b4d8;
font-size: 12px;
}
.log-message {
color: #00ff88;
flex: 1;
}
.log-empty {
color: #00b4d8;
text-align: center;
opacity: 0.5;
}
.modifiers-info {
background: rgba(0, 255, 136, 0.05);
padding: 20px;
border-radius: 8px;
border: 1px solid #00ff88;
}
.modifiers-info h3 {
color: #00ff88;
margin-top: 0;
}
.modifier-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.modifier-item {
color: #00b4d8;
}
.modifier-item strong {
display: block;
color: #00ff88;
margin-bottom: 10px;
}
.modifier-item code {
background: rgba(0, 255, 136, 0.2);
padding: 4px 8px;
border-radius: 4px;
color: #00ff88;
font-size: 12px;
margin-right: 5px;
display: inline-block;
margin-bottom: 5px;
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the .prevent modifier do in @submit.prevent?
2. When do we use the .stop modifier?
These are 2 of 7 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a form with @submit.prevent and a button with @click.once.
- Horizontal ordering
Arrange the syntax for a form with the .prevent modifier:
- Vertical ordering
Arrange the DOM event propagation phases in order:
- Click in order
Click in the correct order to build @click.stop.prevent:
- Code editor
Create an input that responds to @keyup.enter and @keyup.esc.
- Vertical ordering
Arrange the order of event propagation from bottom to top (bubbling):
Tasks after this lesson
- Question.prevent modifier
- Question.stop modifier
- Coding taskPractice: Event modifiers
- Put in order@submit.prevent syntax
- Put in orderDOM event propagation
- Question.once modifier
- Click in orderBuilding @click.stop.prevent
- QuestionKey modifiers
- Coding taskPractice: Key modifiers
- Put in orderEvent propagation
- QuestionCtrl+Enter combination
- Question.right modifier
- QuestionSubmit event in forms