Vue.js course · Module 2: Template Syntax
Conditional Directives
In this lesson4
Just as NOVA LAB systems make decisions based on sensor readings, Vue allows you to control what appears in the interface.
The classes from the previous lesson change how an element looks, but the element still exists. Sometimes the station hologram needs something stronger: show the panel of only the system the operator picked, and display the failure message only during a failure. That is what the conditional directives are for - v-if, which decides whether the element is created at all, and v-show, which only hides it.
v-if, v-else-if, v-else
v-if renders an element only when the expression is truthy. v-else-if adds further conditions, and v-else, which takes no value at all, catches the rest. Both must come immediately after an element with v-if or v-else-if. A <template> tag with v-if lets you put a whole group of elements under one condition:
<template>
<div class="system-monitor" style="background: #0a0e27; color: #00ff88;">
<div v-if="systemType === 'oxygen'">
Oxygen generator - System active
</div>
<div v-else-if="systemType === 'water'">
Water recycling - System active
</div>
<div v-else-if="systemType === 'power'">
Plasma reactor - System active
</div>
<div v-else>
Unknown system
</div>
<!-- On a group of elements -->
<template v-if="showDetails">
<h2 style="color: #00b4d8;">{{ module.name }}</h2>
<p>{{ module.description }}</p>
<span>Status: {{ module.status }}</span>
</template>
</div>
</template>With systemType equal to 'oxygen', only the first div exists in the DOM. The others are not hidden - they simply are not there. The <template> itself is not rendered either: the heading, the paragraph and the span land on the page without an extra wrapper. If another element stood between v-if and v-else, the compiler would report that v-else has no adjacent v-if.
The conditions read ordinary data from the script:
<script setup>
import { ref, reactive } from 'vue'
const systemType = ref('oxygen')
const showDetails = ref(true)
const module = reactive({
name: 'Life Support Alpha',
description: 'Primary oxygen generation system',
status: 'ONLINE'
})
</script>Set systemType.value = 'water', and Vue removes the oxygen element and creates the water one. On every render Vue builds a new Virtual DOM tree, a lightweight description of the page in JavaScript. When the condition is false, the element is missing from that tree. Vue compares the new tree with the previous one and only then adds or removes the real element in the browser. v-if is also lazy: if the condition is false at the start, nothing is rendered, and on every toggle the block's content is destroyed and created from scratch.
v-show
v-show works differently: the element is always rendered, and the directive only toggles the CSS display property.
<template>
<div class="alert-panel">
<!-- v-show - always rendered, just CSS display: none -->
<div v-show="isVisible" class="alert-message"
style="background: #ff4444; color: white; padding: 1rem;">
CRITICAL ALERT: Oxygen levels dropping!
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const isVisible = ref(true)
</script>With isVisible set to false, the element gets style="display: none;", but it stays in the DOM together with its state. v-show does not work on a <template> tag and does not pair with v-else. Most often it is driven by a button that flips a boolean value:
<template>
<button @click="isVisible = !isVisible">Toggle panel</button>
<div v-show="isVisible">Diagnostics panel</div>
</template>Every click turns true into false and back. It is the same in-template statement you met with v-on.
v-if vs v-show
Both directives produce the same effect on screen, but they cost different things:
| Feature | v-if | v-show |
|---|---|---|
| Rendering | Conditional | Always |
| Initial cost | Low | Higher |
| Toggle cost | Higher | Low |
| Use case | Rare changes | Frequent toggling (e.g., alerts) |
The Vue docs give the same advice I do: v-show for things toggled very often, like alerts or tabs, and v-if when the condition rarely changes or the content is heavy and not worth building in advance.
Practical Example
The mission panel combines two chains of conditions: a system filter and the data loading state. The first part of the template holds the filter buttons:
<template>
<div class="mission-dashboard" style="background: #0a0e27; padding: 1rem;">
<div class="system-filter">
<button @click="filter = 'all'" class="btn-filter">All</button>
<button @click="filter = 'life-support'" class="btn-filter">Life Support</button>
<button @click="filter = 'power'" class="btn-filter">Power</button>
</div>
<div v-if="filter === 'all'" class="systems-grid">
All systems...
</div>
<div v-else-if="filter === 'life-support'" class="systems-grid">
Life support systems only...
</div>
<div v-else class="systems-grid">
Power systems only...
</div>Each button assigns a new value to filter, and the chain shows exactly one grid. The second part of the same template handles loading the sensor data:
<!-- Loading state -->
<div v-if="isLoading" class="loader" style="color: #00b4d8;">
Loading sensor data...
</div>
<div v-else-if="error" class="error" style="color: #ff4444;">
{{ error }}
</div>
<div v-else class="content" style="color: #00ff88;">
{{ data }}
</div>
</div>
</template>The order matters: loading first, then the error, and the data last. Four refs drive the whole thing:
<script setup>
import { ref } from 'vue'
const filter = ref('all')
const isLoading = ref(false)
const error = ref(null)
const data = ref('All systems nominal')
</script>Set isLoading.value = true, and the loading message appears instead of the data. In the next lesson you will see v-for and learn why it is not combined with v-if on the same element.
Remember: v-if opens and closes the module hatch, so the element disappears from the DOM, while v-show only draws a curtain behind which the element keeps waiting.
Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
const oxygenLevel = ref(95)
const temperature = ref(-55)
const solarStorm = ref(false)
const crewStatus = ref('all-safe')
const showWarnings = ref(true)
const alertType = computed(() => {
if (oxygenLevel.value < 50) return 'critical'
if (oxygenLevel.value < 80) return 'warning'
return 'safe'
})
function simulateStorm() {
solarStorm.value = true
oxygenLevel.value = 45
temperature.value = -80
crewStatus.value = 'emergency'
}
function normalizeConditions() {
solarStorm.value = false
oxygenLevel.value = 95
temperature.value = -55
crewStatus.value = 'all-safe'
}
function adjustOxygen(value) {
oxygenLevel.value = Math.max(0, Math.min(100, oxygenLevel.value + value))
}
</script>
<template>
<div class="conditions-monitor">
<h1>Conditions Monitor - Mars Base NOVA</h1>
<!-- v-if, v-else-if, v-else -->
<div class="alert-section">
<div v-if="alertType === 'critical'" class="alert alert-critical">
CRITICAL ALARM! Oxygen level below safe level!
</div>
<div v-else-if="alertType === 'warning'" class="alert alert-warning">
WARNING: Oxygen level has dropped below normal.
</div>
<div v-else class="alert alert-safe">
All systems operating normally.
</div>
</div>
<!-- v-show vs v-if -->
<div class="info-panel">
<h2>Difference between v-if and v-show</h2>
<button @click="showWarnings = !showWarnings" class="btn btn-toggle">
Toggle Warnings (v-show)
</button>
<!-- v-show: element stays in DOM, only hidden via CSS -->
<div v-show="showWarnings" class="warning-box">
<p>This warning is controlled by v-show</p>
<p>Element stays in DOM, but is hidden via display: none</p>
</div>
<!-- v-if: element is removed/added from DOM -->
<div v-if="showWarnings" class="warning-box">
<p>This warning is controlled by v-if</p>
<p>Element is completely removed/added from DOM</p>
</div>
</div>
<div class="status-grid">
<!-- Conditional rendering of the storm status -->
<div class="status-card" :class="{ 'storm-active': solarStorm }">
<h3>Solar Storm</h3>
<div v-if="solarStorm" class="storm-warning">
<p class="storm-icon">!!!</p>
<p>ACTIVE SOLAR STORM</p>
<p>All external operations suspended</p>
</div>
<div v-else class="storm-calm">
<p class="calm-icon">OK</p>
<p>Stable conditions</p>
</div>
</div>
<!-- Crew status with multiple conditions -->
<div class="status-card">
<h3>Crew Status</h3>
<div v-if="crewStatus === 'emergency'" class="crew-emergency">
EMERGENCY - Everyone in the shelter
</div>
<div v-else-if="crewStatus === 'alert'" class="crew-alert">
Elevated Alert State
</div>
<div v-else-if="crewStatus === 'all-safe'" class="crew-safe">
All crew safe - Routine operations
</div>
<div v-else class="crew-unknown">
Status unknown
</div>
</div>
<!-- Oxygen level control -->
<div class="status-card">
<h3>Oxygen Level</h3>
<div class="oxygen-display" :class="'oxygen-' + alertType">
{{ oxygenLevel }}%
</div>
<div class="oxygen-controls">
<button @click="adjustOxygen(-10)" class="btn btn-small">-10%</button>
<button @click="adjustOxygen(10)" class="btn btn-small">+10%</button>
</div>
</div>
<!-- Temperature -->
<div class="status-card">
<h3>Temperature</h3>
<div class="temp-display">{{ temperature }}°C</div>
<div v-if="temperature < -70" class="temp-warning">
Extremely low temperatures
</div>
</div>
</div>
<div class="controls-section">
<h2>Conditions Simulation</h2>
<div class="button-group">
<button @click="simulateStorm" class="btn btn-danger">
Simulate Solar Storm
</button>
<button @click="normalizeConditions" class="btn btn-success">
Restore Normal Conditions
</button>
</div>
</div>
<div class="info-box">
<h3>Conditional Rendering in Vue</h3>
<ul>
<li><strong>v-if</strong> - Renders the element only when condition is true (removes from DOM)</li>
<li><strong>v-else-if</strong> - Additional conditions in the chain</li>
<li><strong>v-else</strong> - Default case</li>
<li><strong>v-show</strong> - Always in DOM, hides via CSS (better for frequent changes)</li>
</ul>
</div>
</div>
</template>
<style scoped>
.conditions-monitor {
background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
min-height: 100vh;
padding: 2rem;
color: #ffffff;
font-family: 'Courier New', monospace;
}
h1 {
text-align: center;
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.5);
margin-bottom: 2rem;
}
.alert-section {
margin-bottom: 2rem;
}
.alert {
padding: 1.5rem;
border-radius: 10px;
font-size: 1.2rem;
font-weight: bold;
text-align: center;
animation: slideIn 0.5s ease;
}
@keyframes slideIn {
from { transform: translateY(-20px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.alert-critical {
background: rgba(255, 0, 85, 0.2);
border: 3px solid #ff0055;
animation: pulse 1s infinite;
}
.alert-warning {
background: rgba(255, 180, 0, 0.2);
border: 3px solid #ffb400;
}
.alert-safe {
background: rgba(0, 255, 136, 0.2);
border: 3px solid #00ff88;
}
.info-panel {
background: rgba(0, 180, 216, 0.1);
border: 2px solid #00b4d8;
border-radius: 10px;
padding: 1.5rem;
margin-bottom: 2rem;
}
.warning-box {
background: rgba(255, 180, 0, 0.1);
border: 2px solid #ffb400;
border-radius: 5px;
padding: 1rem;
margin-top: 1rem;
}
.status-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
.status-card {
background: rgba(0, 255, 136, 0.1);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 1.5rem;
transition: all 0.3s ease;
}
.status-card.storm-active {
border-color: #ff0055;
background: rgba(255, 0, 85, 0.2);
animation: shake 0.5s infinite;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
.status-card h3 {
color: #00b4d8;
margin-top: 0;
}
.storm-warning, .storm-calm {
text-align: center;
}
.storm-icon {
font-size: 3rem;
margin: 0;
animation: flicker 0.3s infinite;
}
@keyframes flicker {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.calm-icon {
font-size: 3rem;
margin: 0;
}
.crew-emergency {
color: #ff0055;
font-weight: bold;
padding: 1rem;
background: rgba(255, 0, 85, 0.2);
border-radius: 5px;
}
.crew-alert {
color: #ffb400;
font-weight: bold;
}
.crew-safe {
color: #00ff88;
font-weight: bold;
}
.oxygen-display {
font-size: 3rem;
text-align: center;
font-weight: bold;
margin: 1rem 0;
}
.oxygen-critical {
color: #ff0055;
animation: pulse 1s infinite;
}
.oxygen-warning {
color: #ffb400;
}
.oxygen-safe {
color: #00ff88;
}
.oxygen-controls {
display: flex;
gap: 1rem;
justify-content: center;
}
.temp-display {
font-size: 2.5rem;
text-align: center;
color: #00b4d8;
margin: 1rem 0;
}
.temp-warning {
color: #00b4d8;
text-align: center;
font-size: 0.9rem;
}
.controls-section {
background: rgba(255, 255, 255, 0.05);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 1.5rem;
margin-bottom: 2rem;
}
.button-group {
display: flex;
gap: 1rem;
justify-content: center;
flex-wrap: wrap;
}
.btn {
padding: 1rem 2rem;
border: none;
border-radius: 5px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
font-family: 'Courier New', monospace;
}
.btn-toggle {
background: #00b4d8;
color: #ffffff;
}
.btn-danger {
background: #ff0055;
color: #ffffff;
}
.btn-success {
background: #00ff88;
color: #0a0e27;
}
.btn-small {
padding: 0.5rem 1rem;
font-size: 0.9rem;
background: #00b4d8;
color: #ffffff;
}
.btn:hover {
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0, 255, 136, 0.4);
}
.info-box {
background: rgba(0, 255, 136, 0.05);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 1.5rem;
}
.info-box h3 {
color: #00ff88;
margin-top: 0;
}
.info-box ul {
list-style: none;
padding: 0;
}
.info-box li {
padding: 0.5rem 0;
color: #ffffff;
border-left: 3px solid #00b4d8;
padding-left: 1rem;
margin: 0.5rem 0;
}
.info-box strong {
color: #00b4d8;
}
</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 is the difference between v-if and v-show?
2. When is it better to use v-show instead of v-if?
3. Can you use v-else-if in Vue?
4. Which code snippet correctly uses v-if with v-else?
5. What happens to a DOM element when the v-if condition is set to false?
Hands-on tasks in the game
- Code editor
Use v-if, v-else-if, and v-else for conditional rendering of system statuses.
- Vertical ordering
Arrange the correct conditional chain from v-if to v-else:
- Vertical ordering
Order the steps of v-if from condition check to rendering:
- Click in order
Arrange the syntax: first the toggle button, then the element with v-show below it:
- Code editor
Use v-show with a toggle button to hide/show sections.
Tasks after this lesson
- QuestionDifference: v-if vs v-show
- QuestionWhen to Use v-show
- Coding taskPractice: v-if Conditional Rendering
- Put in orderv-if Conditional Chain
- QuestionThe v-else-if Directive
- Questionv-if with v-else Syntax
- Put in orderConditional Rendering Steps
- Click in orderv-show Syntax with Toggle
- Coding taskPractice: v-show Toggle
- QuestionElement Behavior with v-if false