Vue.js course ยท Module 5: Events & Forms
Event Handling - Control Buttons
In this lesson5
Welcome to the NOVA LAB Control Simulator! Until now the station's panels only displayed data: they calculated, filtered and reported. The crew, however, has to operate them, and a button that does not react to a click is nothing more than decoration. In plain JavaScript every button would require finding the element, attaching a listener with addEventListener and remembering to remove it when the panel disappears. Vue does this for you with a single directive.
What you will learn
- event handling - how to hook a procedure up to a button, a key or a mouse movement.
- event modifiers - how to block a page reload, stop propagation and react to specific keys.
- v-model - how to bind form fields to variables in both directions.
- v-model modifiers - how to clean up the signal from fields with
.lazy,.numberand.trim. - advanced forms - selecting multiple options, options generated from an array, and validation.
- forms in practice and the project - a complete module registration and a mission registration panel.
Basic Event Handling
The v-on directive listens for a DOM event and runs code when it happens. The full form is v-on:click, and the shorthand used every day is @click. The value can be the name of a function, a method handler, or a short piece of JavaScript, an inline handler. Vue tells them apart by itself: a name like handleClick or a path like panel.start is a method, and anything else, for example count++ or initiateSystem('OXYGEN'), is inline code. First, the panel template with five button variants.
<template>
<div class="control-panel" style="background: #0a0e27; color: #00ff88;">
<!-- Full syntax -->
<button v-on:click="handleClick" style="background: #00b4d8; color: #0a0e27;">Activate</button>
<!-- Shorthand syntax (recommended) -->
<button @click="handleClick" style="background: #00b4d8; color: #0a0e27;">Activate</button>
<!-- Inline handler -->
<button @click="powerLevel++" style="background: #00b4d8; color: #0a0e27;">Power: {{ powerLevel }}%</button>
<!-- With argument -->
<button @click="initiateSystem('OXYGEN')" style="background: #00b4d8; color: #0a0e27;">Start O2</button>
<!-- With event object -->
<button @click="logEvent($event)" style="background: #00b4d8; color: #0a0e27;">Log Command</button>
</div>
</template>The first two buttons do exactly the same thing and differ only in notation. The third one increments powerLevel directly in the template. The fourth calls a function with an argument, and the fifth passes it the special $event variable, which Vue fills with the native event object. Now the script with the functions these buttons call.
<script setup>
import { ref } from 'vue'
const powerLevel = ref(0)
function handleClick() {
console.log('System activated!')
}
function initiateSystem(systemName) {
console.log(`Initializing ${systemName} system...`)
}
function logEvent(event) {
console.log('Event:', event.type, event.target)
}
</script>Look at handleClick: in the template we gave just the name, without parentheses, so Vue calls the function and passes it the event object as the first argument. We do not use it here, but it is available. What did not change compared to plain JavaScript: these are still ordinary functions and ordinary browser events. Vue only adds attaching the listener and removing it automatically when the component leaves the page.
The event and your own argument
Sometimes a procedure needs both the event object and a piece of information of its own, such as the name of a system. In an inline handler you then pass $event next to the argument. An equivalent form is an arrow function that receives the event as a parameter.
<template>
<button @click="logAction($event, 'oxygen')">Log O2</button>
<button @click="(event) => logAction(event, 'water')">Log H2O</button>
</template>
<script setup>
function logAction(event, system) {
console.log(system, event.type)
}
</script>Both buttons call the same function and print the system name and the event type, which is click. You choose the order of the arguments yourself, as long as it matches the function definition. Remember that in an inline handler only $event means the event - a plain event or e is an unknown variable to the template.
Common Events
After @ you can type the name of any DOM event. The template below is a catalog of the most common ones: mouse, keyboard and form events, plus scrolling and image loading. We left out the handler functions, because only the event names matter here.
<template>
<!-- Mouse events -->
<div @click="onClick" @dblclick="onDoubleClick">Click</div>
<div @mouseenter="onEnter" @mouseleave="onLeave">Hover</div>
<div @mousedown="onDown" @mouseup="onUp">Press</div>
<!-- Keyboard events -->
<input @keydown="onKeyDown" @keyup="onKeyUp" @keypress="onKeyPress" />
<!-- Form events -->
<form @submit="onSubmit">
<input @input="onInput" @change="onChange" @focus="onFocus" @blur="onBlur" />
</form>
<!-- Other -->
<div @scroll="onScroll">Scrollable content</div>
<img @load="onLoad" @error="onError" :src="imageUrl" />
</template>mouseenter and mouseleave report the cursor entering and leaving an element, and unlike mouseover they do not fire again when the cursor moves between the elements inside. input arrives after every change of a field's content, and change after the change is committed. focus and blur mean entering and leaving a field. Watch out for keypress: according to MDN this event is deprecated, so use keydown in new code. Vue does not invent events of its own here - they are all native browser events.
Accessing the Event Object
A method handler receives the event object automatically as its first parameter. The most useful properties are: target, the element on which the event happened, clientX and clientY with the cursor position in the window, buttons with a mask of the pressed mouse buttons, and for the keyboard key, code and the ctrlKey and shiftKey flags.
<template>
<button @click="handleClick">Click</button>
<input @keyup="handleKey" />
</template>
<script setup>
function handleClick(event) {
console.log('Target:', event.target)
console.log('Position:', event.clientX, event.clientY)
console.log('Buttons:', event.buttons)
}
function handleKey(event) {
console.log('Key:', event.key)
console.log('Code:', event.code)
console.log('Ctrl:', event.ctrlKey)
console.log('Shift:', event.shiftKey)
}
</script>key gives the value of the key, for example "Enter" or "a", and code its physical place on the keyboard, for example "KeyA", regardless of the layout. For shortcuts that respond to a character I recommend key, because the key modifiers from the next lesson are built on it. Choose code for controls that depend on key positions, such as WASD. With buttons, keep in mind that during a click event the button may already be released, and the button that triggered the event is reported by the button property.
Remember: @ is the cable between a button on the panel and a procedure in the onboard computer - you give it the name of a function or a short command, and Vue plugs the cable in and unplugs it by itself.
Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'
const signalsSent = ref(0)
const lastSignalType = ref('')
const emergencyActive = ref(false)
const sendSignal = (type) => {
signalsSent.value++
lastSignalType.value = type
}
const activateEmergency = (event) => {
event.preventDefault()
emergencyActive.value = true
setTimeout(() => {
emergencyActive.value = false
}, 3000)
}
const sendOnce = () => {
console.log('One-time signal sent!')
}
</script>
<template>
<div class="communication-panel">
<div class="panel-header">
<h2>NOVA LAB Communication Panel</h2>
<p class="subtitle">Communication Zone - Event Handling</p>
</div>
<div class="stats">
<div class="stat-item">
<span class="label">Signals sent:</span>
<span class="value">{{ signalsSent }}</span>
</div>
<div class="stat-item">
<span class="label">Last type:</span>
<span class="value">{{ lastSignalType || 'None' }}</span>
</div>
</div>
<div class="signal-buttons">
<button @click="sendSignal('Routine')" class="signal-btn routine">
Routine Signal
</button>
<button @click="sendSignal('Urgent')" class="signal-btn urgent">
Urgent Signal
</button>
<button @click.once="sendOnce" class="signal-btn once">
One-time (.once)
</button>
</div>
<div class="emergency-section">
<a href="#" @click.prevent="activateEmergency" class="emergency-link">
Activate Alarm (.prevent)
</a>
<div v-if="emergencyActive" class="emergency-alert">
ALARM ACTIVE!
</div>
</div>
<div class="event-info">
<h3>Event modifiers:</h3>
<ul>
<li><code>.prevent</code> - prevents the default action</li>
<li><code>.stop</code> - stops event propagation</li>
<li><code>.once</code> - the event fires only once</li>
</ul>
</div>
</div>
</template>
<style scoped>
.communication-panel {
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: 800px;
margin: 0 auto;
}
.panel-header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #00b4d8;
}
.panel-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;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
margin-bottom: 30px;
}
.stat-item {
background: rgba(0, 180, 216, 0.1);
padding: 15px;
border-radius: 8px;
border: 1px solid #00b4d8;
display: flex;
justify-content: space-between;
align-items: center;
}
.label {
color: #00b4d8;
font-size: 14px;
}
.value {
color: #00ff88;
font-size: 20px;
font-weight: bold;
}
.signal-buttons {
display: grid;
gap: 15px;
margin-bottom: 30px;
}
.signal-btn {
background: linear-gradient(135deg, #00b4d8 0%, #0077b6 100%);
color: white;
border: none;
padding: 15px 30px;
border-radius: 8px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
font-family: 'Courier New', monospace;
}
.signal-btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 180, 216, 0.4);
}
.signal-btn.urgent {
background: linear-gradient(135deg, #ff6b35 0%, #d64545 100%);
}
.signal-btn.once {
background: linear-gradient(135deg, #9d4edd 0%, #7209b7 100%);
}
.emergency-section {
text-align: center;
margin-bottom: 30px;
padding: 20px;
background: rgba(255, 107, 53, 0.1);
border-radius: 8px;
border: 1px solid #ff6b35;
}
.emergency-link {
color: #ff6b35;
font-size: 18px;
text-decoration: none;
font-weight: bold;
padding: 10px 20px;
display: inline-block;
border: 2px solid #ff6b35;
border-radius: 8px;
transition: all 0.3s ease;
}
.emergency-link:hover {
background: rgba(255, 107, 53, 0.2);
transform: scale(1.05);
}
.emergency-alert {
margin-top: 15px;
padding: 15px;
background: #ff6b35;
color: white;
border-radius: 8px;
font-weight: bold;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
.event-info {
background: rgba(0, 255, 136, 0.05);
padding: 20px;
border-radius: 8px;
border: 1px solid #00ff88;
}
.event-info h3 {
color: #00ff88;
margin-top: 0;
font-size: 18px;
}
.event-info ul {
margin: 0;
padding-left: 20px;
}
.event-info li {
color: #00b4d8;
margin: 8px 0;
}
.event-info code {
background: rgba(0, 255, 136, 0.2);
padding: 2px 6px;
border-radius: 4px;
color: #00ff88;
font-weight: bold;
}
</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. How do you add a click event listener in Vue.js?
2. What symbol is a shorthand for the v-on directive?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Add a @click handler that increments a counter and display the value.
- Click in order
Arrange the syntax for adding a click handler in Vue:
- Code editor
Add @mouseenter, @mouseleave, and @dblclick handlers to a div element.
- Horizontal ordering
Arrange the correct syntax for a handler passing event and argument: