An interface changes shape depending on the situation: while the data is loading it shows an indicator; if something fails, an error message with a button to try again; if there are no results, a notice; and only when all is well, the data. So far in Colmena Bookings we have handled this with nested ternaries inside an interpolation and with paragraphs that exist even when they are empty. In this lesson you will learn the directives that decide whether an element exists or not (v-if, v-else-if, v-else) and the one that decides whether it is visible or not (v-show), you will understand the fundamental difference between them and how they relate to the component lifecycle, and you will apply the loading / error / empty / data states pattern to loading the room catalogue.
Contents
v-if: rendering an element only if a condition is metv-else-ifandv-else- Grouping several elements with
<template v-if> v-show: showing or hiding without destroyingv-ifversusv-show- Conditional rendering and the lifecycle
v-iftogether withv-for: why not on the same element- The states pattern: loading, error, empty and data
- Case study: catalogue states, occupancy notices and the reception clock
v-if: rendering an element only if a condition is met
v-if: rendering an element only if a condition is metThe v-if directive evaluates an expression and only creates the element if the result is truthy:
<script setup>
import { ref } from 'vue'
const loading = ref(true)
</script>
<template>
<p v-if="loading">Loading rooms…</p>
</template>When loading is false, the paragraph does not exist in the DOM: it is not hidden, it has simply not been created. If loading later becomes true again, Vue creates it anew. Inspect the page with the browser's developer tools and you will see, in its place, a <!--v-if--> comment that Vue uses as a placeholder.
You already used v-if in the lesson on the Vue instance to mount and unmount ReceptionClock, and in the RoomCard draft we left as a pending task not generating the notice paragraph when it was empty. Now you can do it:
An empty string is falsy, so the paragraph only exists when there is a notice.
v-else-if and v-else
v-else-if and v-elseTo chain alternatives, use v-else-if and v-else, with the same logic as if / else if / else in JavaScript:
<template>
<p v-if="freeSeats === 0" class="notice">Room full</p>
<p v-else-if="freeSeats <= 2" class="notice">Last few seats!</p>
<p v-else>{{ freeSeats }} seats left</p>
</template>Rules:
v-else-ifandv-elsemust be on the element immediately following av-iforv-else-if. There can be no other element in between (comments are allowed).v-elsetakes no value.- The conditions are evaluated in order and only one branch is rendered: the first whose condition is true, or the
v-elseone.
<!-- ERROR: there is a <span> between the v-if and the v-else -->
<p v-if="loading">Loading…</p>
<span>Catalogue</span>
<p v-else>Ready</p>In that case Vue shows a compilation error: v-else has no adjacent v-if.
Compared with a ternary inside an interpolation, v-if/v-else lets each branch have its own markup: different tags, classes, buttons...
- Grouping several elements with
<template v-if>
<template v-if>What if a condition controls several elements? You could wrap them in a <div>, but that adds an unnecessary element to the DOM that can spoil the layout (for example, in a grid or a list). The solution is the <template> element, which groups them without leaving a trace:
<template v-if="!loading">
<h3>Catalogue</h3>
<p>{{ freeRooms }} free rooms</p>
<p>{{ catalogNames }}</p>
</template>
<p v-else>Loading rooms…</p>- When the condition is true, the
<h3>and the two<p>elements are rendered, without any container around them. <template>also works withv-else-ifandv-else.- Do not confuse this inner
<template>with the component's root<template>block: this one is an invisible grouping element inside the template.
v-show: showing or hiding without destroying
v-show: showing or hiding without destroyingv-show also shows or hides an element according to a condition, but in a completely different way:
- The element is always created when the component renders, whatever the condition.
- When the condition is false, Vue applies the inline style
display: noneto it. When it is true, it removes it. - The element remains in the DOM the whole time: only its visibility changes.
Limitations:
v-showdoes not supportv-elseorv-else-if.- It does not work on
<template>, because<template>does not generate any element to whichdisplay: nonecould be applied. - If your CSS gives the element a
displaywith higher priority (for example, with!important), it can stop it from being hidden.
v-if versus v-show
v-if versus v-show| Aspect | v-if |
v-show |
|---|---|---|
| What it does when the condition is false | Does not create the element (or destroys it if it existed) | Creates it anyway and applies display: none |
| Initial cost | Low if the condition starts off false (nothing is created) | The full creation cost is always paid |
| Cost of toggling | High: destroying and recreating elements and components | Very low: changing a style |
| Component lifecycle | Mounted and unmounted with every change | Mounted once and kept alive even while hidden |
| Internal state (fields, counters...) | Lost when hidden | Preserved |
v-else / v-else-if |
Yes | No |
On <template> |
Yes | No |
Rule of thumb:
v-showif the element is toggled frequently (tabs, drop-down menus, help panels) and you want to keep its state.v-ifif the condition rarely changes during the component's lifetime, if it is usually false at first (you will not pay for something that may never be shown), if you needv-elsebranches, or if you want the component to release its resources when it is hidden.
- Conditional rendering and the lifecycle
The difference between v-if and v-show becomes crucial with components. Remember what you saw in Understanding the Vue Instance:
sequenceDiagram
participant A as App.vue
participant R as ReceptionClock
Note over A,R: With v-if
A->>R: condition true: an instance is created and mounted (onMounted)
A->>R: condition false: it is unmounted (onUnmounted) and the instance is destroyed
A->>R: condition true: a NEW instance is created, with its initial state
Note over A,R: With v-show
A->>R: created and mounted only once
A->>R: condition false: display none (still alive, its timer keeps running)
A->>R: condition true: visible again, with the same state
Practical consequences:
- With
v-if, theonMounted/onUnmountedhooks run on every toggle. This is what allowsReceptionClockto stop itssetIntervalwhen it is hidden. - With
v-show, the component is never unmounted: its timer keeps running even though nobody can see the clock, and its data is preserved. - With
v-if, the internal state is lost: if you hideRoomCardwithv-ifand show it again, the attendees go back to 0. Withv-show, they are preserved.
Neither is "better": it depends on whether you want to keep the state or release resources.
A technical detail: when two
v-if/v-elsebranches contain elements of the same type (for example, two<input>elements), Vue 3 automatically gives them different keys, so it does not reuse the element from one branch in the other. Vue 2 did, and you had to add akeyby hand to stop a field from keeping its text when switching branches.
v-if together with v-for: why not on the same element
v-if together with v-for: why not on the same elementIn the next lesson you will learn v-for for repeating elements. It is tempting to combine it with v-if on the same element to show only some of them:
<!-- WRONG! -->
<li v-for="room in catalog" v-if="room.available" :key="room.id">{{ room.name }}</li>Do not do it. When both are on the same element, v-if is evaluated before v-for (in Vue 3; in Vue 2 it was the other way round). This means that when room.available is evaluated, the loop variable room does not exist yet, and you will get an error. What is more, the official style guide advises against it because it mixes two responsibilities.
The correct solutions, which you will see in detail in List Rendering, are:
- Filtering beforehand with a computed property (
availableRooms) and looping over the result. This is the preferred one. - Moving the
v-forto a wrapping<template>and leaving thev-ifon the inner element. - Moving the
v-ifto an outer element if what you want is to hide the whole list (for example,<ul v-if="catalog.length">).
- The states pattern: loading, error, empty and data
Any data that arrives asynchronously (from an API, from a file) goes through several states, and the interface must have a response for each one:
stateDiagram-v2
[*] --> Loading: the request is sent
Loading --> Error: the request fails
Loading --> Empty: an empty list arrives
Loading --> Data: results arrive
Error --> Loading: the user clicks Retry
Empty --> Loading: the filter changes
Data --> Loading: the filter changes
| State | Typical condition | What to show |
|---|---|---|
| Loading | loading === true |
A loading indicator (text, spinner or skeleton) |
| Error | error !== '' |
An understandable message and a retry button |
| Empty | data.length === 0 |
An explanatory message and, where appropriate, how to change the filters |
| Data | In any other case | The content |
In the template, this translates into a v-if / v-else-if / v-else chain in that order:
<p v-if="loading">Loading…</p>
<p v-else-if="error">Error: {{ error }}</p>
<p v-else-if="data.length === 0">No results.</p>
<ul v-else>...</ul>The order matters: while loading, data may be empty, and we do not want to say "No results" when in fact we do not know yet. Checking loading and error first avoids that false message. Forgetting the empty state is one of the most frequent oversights: the user sees a blank area and does not know whether the application is working.
- Case study: catalogue states, occupancy notices and the reception clock
9.1 Catalogue states in App.vue
Remember the line we left in Computed Properties and Watchers:
We are going to replace it with the states pattern. First, add a function to the App.vue script to retry loading after an error:
loadRooms already accepted the cancellation signal as an optional second parameter; here we do not pass it because the "Retry" button only appears when there is no request in progress.
Now, the catalogue section of the template:
<section class="catalog">
<h2>Catalogue</h2>
<p>
<!-- ... the four floor buttons, unchanged ... -->
</p>
<p v-if="loading" class="state">Loading rooms…</p>
<div v-else-if="error" class="state state--error" role="alert">
<p>{{ error }}</p>
<button class="button" @click="reloadRooms">Retry</button>
</div>
<p v-else-if="catalog.length === 0" class="state">
There are no rooms on this floor. Try "All".
</p>
<template v-else>
<p>{{ catalogNames }}</p>
<p><strong>{{ freeRooms }}</strong> free rooms out of {{ catalog.length }}</p>
<p>
Rooms that fit {{ seats.booked }} people:
{{ roomsWithCapacity.map((room) => room.name).join(', ') }}
</p>
</template>
</section>And the corresponding styles in the <style scoped> of App.vue:
.state {
padding: 0.75rem 1rem;
border-radius: 6px;
background: white;
}
.state--error {
border-left: 4px solid #c62828;
color: #c62828;
}- Four states, four branches, in the correct order: loading, error, empty and data.
role="alert"makes screen readers announce the error as soon as it appears.<template v-else>groups the three data paragraphs without adding a container. The free-rooms counter no longer shows a misleading "0 free rooms out of 0" while loading.- The "Retry" button calls
reloadRooms. To test it, temporarily raiseERROR_PROBABILITYto1insrc/api/rooms.js: you will see the error every time. Then set it back to0.1. - To see the empty state, open Vue DevTools, select
Appand changefloorFilterto4(a floor that does not exist). The corresponding message will appear.
9.2 Occupancy notices for the selected room
In the .selection section, add a chain of notices after the booked seats paragraph:
<p>Booked seats: {{ seats.booked }} / {{ selectedRoom.capacity }}</p>
<p v-if="!selectedRoom.available" class="notice">This room is under maintenance.</p>
<p v-else-if="freeSeats === 0" class="notice">Room full: no seats left.</p>
<p v-else-if="freeSeats <= 2" class="notice notice--mild">
{{ freeSeats === 1 ? 'Last seat!' : `Last ${freeSeats} seats!` }}
</p>- There is no
v-else: if the room is available and more than 2 seats are left, no notice is shown. - Once again the order matters: a room under maintenance has all its seats free, but the relevant notice is the maintenance one.
- Try it with the Polen Room (4 seats): book 2 and "Last 2 seats!" will appear; 3, "Last seat!"; 4, "Room full".
9.3 The RoomCard notice
In src/components/RoomCard.vue, finally deliver on what we announced in 01-05:
<!-- Before: <p class="notice">{{ notice }}</p> -->
<p v-if="notice" class="notice">{{ notice }}</p>And in its <style scoped>, remove the min-height: 1.5em line from .notice, which only served to reserve the space for the empty paragraph.
9.4 The reception clock: v-if or v-show?
In the header we have <ReceptionClock v-if="showClock" />. Let's run an experiment so that we can decide with sound judgement. In src/components/ReceptionClock.vue, temporarily add a console.log('tick') inside updateTime. Then, in App.vue, change v-if to v-show:
Open the console and click "Show/hide clock" several times:
| Observation | With v-if |
With v-show |
|---|---|---|
| Mounting/unmounting messages when toggling | They appear on every change | Only the mounting one, once |
tick while the clock is hidden |
Stops | Keeps appearing every second |
| The element in the inspector when hidden | A <!--v-if--> comment |
<p class="clock" style="display: none;"> |
For the clock, v-if is the better option: the user toggles it rarely, recreating it is cheap and, when it is hidden, it releases the timer. Put v-if back and remove the console.log('tick').
A case where v-show does fit is a help text that is toggled often. Add this to App.vue:
<button class="button" @click="showHelp = !showHelp">?</button>
<p v-show="showHelp" class="note">
Shift + click on "Book a seat" books 5 seats in one go. In the search box, Enter applies the
search and Escape clears it.
</p>It is a static paragraph, cheap to keep in the DOM, which the user may open and close often: the typical case for v-show.
Common Mistakes and Tips
- Putting something between a
v-ifand itsv-else. The compiler rejects it. The elements in the chain must be consecutive siblings. - Using
v-showwithv-elseor on<template>. It does not work; for that you needv-if. - Checking the empty state before the loading state. You will show "No results" while the data is still arriving.
- Forgetting the empty or error state. The interface is left blank with no explanation.
- Using
v-showon components with timers, subscriptions or requests. They keep working even while hidden, consuming resources. - Using
v-ifon something that is toggled constantly and is expensive to create. Each toggle destroys and rebuilds it; considerv-show. - Combining
v-ifandv-foron the same element.v-ifis evaluated first and cannot see the loop variable. - Tip: when a
v-ifcondition gets long (!loading && !error && catalog.length > 0 && ...), give it a name with a computed property (hasResults). The template will read like a sentence.
Exercises
Exercise 1. Add a "Hide card / Show card" button to App.vue that toggles the visibility of <RoomCard />. Try it first with v-if and then with v-show: add 3 attendees on the card, hide it and show it again. Explain the difference you observe. The button text must change according to the state.
Exercise 2. In the catalogue section, the data branch shows "Rooms that fit N people: ...". If seats.booked is 0 the sentence is odd ("fit 0 people"). Use v-if/v-else inside the <template v-else> to show that line only when seats have been booked, and otherwise a text inviting the user to book.
Exercise 3. This snippet has two mistakes. Find them and fix them:
<p v-show="loading">Loading…</p>
<p v-else>{{ catalogNames }}</p>
<template v-show="!error">
<p>{{ freeRooms }} free rooms</p>
<p>{{ catalog.length }} rooms in total</p>
</template>Solutions
Solution 1.
<button class="button" @click="showCard = !showCard">
{{ showCard ? 'Hide card' : 'Show card' }}
</button>
<RoomCard v-if="showCard" />- With
v-if: when it is hidden, theRoomCardinstance is destroyed; when it is shown, a new one is created. The attendees go back to 0 and "[RoomCard] Panal Room ready" (itsonMounted) appears in the console again. - With
v-show(<RoomCard v-show="showCard" />): the card is only hidden withdisplay: none. When it is shown, the 3 attendees are still there, and the mounting message is not repeated.
Notice that v-show works on a component because RoomCard has a single root element (<article>), to which Vue applies the display: none.
Solution 2.
<template v-else>
<p>{{ catalogNames }}</p>
<p><strong>{{ freeRooms }}</strong> free rooms out of {{ catalog.length }}</p>
<p v-if="seats.booked > 0">
Rooms that fit {{ seats.booked }} people:
{{ roomsWithCapacity.map((room) => room.name).join(', ') }}
</p>
<p v-else>Book seats to see which rooms your group fits into.</p>
</template>Conditionals can be nested: a v-if/v-else inside a branch of another one.
Solution 3.
v-elsecannot follow av-show, only av-if/v-else-if. You need to usev-if="loading"on the first paragraph.v-showdoes not work on<template>(there is no element to whichdisplay: nonecould be applied). Usev-ifon the<template>, orv-showon a real element such as a<div>.
<p v-if="loading">Loading…</p>
<p v-else>{{ catalogNames }}</p>
<template v-if="!error">
<p>{{ freeRooms }} free rooms</p>
<p>{{ catalog.length }} rooms in total</p>
</template>Conclusion
v-if, v-else-if and v-else decide whether an element exists: they create or destroy elements and components (with their mounting and unmounting hooks), support chained branches and can group several elements with <template v-if>. v-show decides whether an element is visible: it always creates it and toggles display: none, which makes it ideal for frequent toggling and for preserving state, at the cost of keeping hidden components alive. You know why v-if and v-for should not go on the same element and you know the loading, error, empty and data states pattern, in that order. In Colmena Bookings, the catalogue shows a clear state in every situation with an option to retry, the selected room warns about maintenance and the last few seats, RoomCard only generates the notice when there is one, and the reception clock keeps a well-justified v-if.
In the data branch we are still showing the rooms as a comma-separated list of names, and the floor buttons are written out by hand one by one. In the next lesson, List Rendering, you will learn v-for to display the catalogue as a real list, with filters by capacity and equipment and sorting by price.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
