Conditional rendering with v-if and v-show
Showing and hiding parts of a template with v-if, v-else-if, v-else and v-show, and choosing between creating elements and toggling their display.
Conditional rendering with v-if and v-show
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `v-if` really adds and removes elements. When its condition is false the element and everything inside it do not exist in the DOM, and any components inside are unmounted, losing their state.
- `v-else-if` and `v-else` must sit on the element immediately after a `v-if` or `v-else-if` sibling; anything in between breaks the chain.
- Putting `v-if` on a `<template>` element toggles a group of elements without adding a wrapper to the DOM.
- `v-show` always renders the element and toggles only its inline `display` style. It does not work on `<template>` and has no `v-else` partner.
- Pick `v-if` when the condition rarely changes or the hidden content is expensive, and `v-show` when something toggles often and its state should survive being hidden.
- Avoid putting `v-if` and `v-for` on the same element. In Vue 3 `v-if` is evaluated first, so it cannot see the loop variable.
The problem: one template, several states
Real interfaces spend most of their time in one of several states. A product is in stock or sold out. A request is loading, failed, or done. A user is signed in or not. You could render every possibility and hide the irrelevant ones with CSS, but that leaves dead markup in the page and work being done for content nobody sees. What you want is for the template to say “render this part only when this is true”.
Vue gives you two ways to do that, and they differ in one important respect: whether the hidden content exists at all.
v-if, v-else-if, v-else
v-if takes an expression and renders its element only when the expression is truthy:
<script setup>
import { ref } from 'vue'
const stock = ref(3)
</script>
<template>
<p v-if="stock > 10">In stock</p>
<p v-else-if="stock > 0">Only {{ stock }} left</p>
<p v-else>Sold out</p>
</template>
This reads like an if / else if / else block, and it behaves like one: exactly one of the three paragraphs exists at a time. The chain has a strict structural rule. v-else-if and v-else must be on the element immediately following a v-if or v-else-if sibling. Put any other element between them and the compiler rejects the template.
When the condition is false, the element is not hidden; it is never created. Nothing in the DOM, no listeners, no child components. If it starts out false, Vue does no work for it until it first becomes true. When a condition flips from true to false, Vue destroys the element and unmounts any components inside it, running their unmount hooks (covered in lifecycle hooks). Any state inside, such as text typed into an input or a child component’s local data, is thrown away. The next time the condition is true you get a brand-new copy.
Vue 3 also gives each branch of a v-if chain its own automatic key. If the v-if branch and the v-else branch both contain an <input>, switching branches creates a separate input rather than reusing the first one with its old value. In Vue 2 you had to add key by hand to get that.
Toggling a group with template
v-if attaches to one element. To toggle several siblings together without adding a wrapper <div> that might break your layout or your CSS selectors, put it on a <template>:
<template v-if="user">
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
<button @click="signOut">Sign out</button>
</template>
<button v-else @click="signIn">Sign in</button>
The <template> element is an invisible grouping. It never appears in the rendered DOM; only its children do.
v-show: always there, sometimes hidden
v-show looks similar but does something different:
<div v-show="filtersOpen" class="filters">
<!-- ... -->
</div>
The element is rendered once, regardless of the condition, and stays in the DOM. v-show only toggles its inline display style between none and its normal value. Nothing is created or destroyed, components inside are not unmounted, and their state survives.
Two restrictions follow from that design. v-show cannot go on a <template>, because a template has no element of its own to put a style on. And there is no v-else for it; to show one of two things, give each its own v-show with opposite conditions.
One subtle consequence: when shown, v-show restores whatever inline display the element had before, which is usually none at all. It never forces a visible value, so if a stylesheet rule hides the element, v-show="true" will not override it.
Choosing between them
Think of it like a restaurant kitchen. v-if is cooking a dish to order: nothing exists until someone asks, and leftovers go in the bin. v-show is keeping a dish under a heat lamp: it costs something up front, but serving it again is instant.
v-if |
v-show |
|
|---|---|---|
| Hidden content in the DOM | No | Yes, with display: none |
| Initial cost when false | None | Full render |
| Cost of each toggle | Create or destroy everything inside | Change one style |
| State inside survives hiding | No | Yes |
Works on <template>, has v-else |
Yes | No |
The rule of thumb that follows: use v-if when the condition rarely changes, when the hidden content is expensive or should not exist (an admin-only panel, say), or when you need v-else. Use v-show for things toggled often, like a dropdown, a tab panel, or a filter drawer, especially if you want their internal state preserved. If you want state preserved with v-if-style mounting, KeepAlive is the tool for components.
Not on the same element as v-for
It is tempting to filter a list by putting both directives on one element. Do not:
<!-- Error: user is not defined when v-if runs -->
<li v-for="user in users" v-if="user.active">{{ user.name }}</li>
In Vue 3, v-if takes priority over v-for on the same element, so the condition is evaluated before the loop variable exists. Vue 2 had the opposite priority, which is why older tutorials sometimes show this pattern. The fixes, filtering in a computed property or moving the loop to a wrapping <template>, are covered in list rendering with v-for.
Compared with React
React has no directive for this. You use plain JavaScript, cond && <X /> or a ternary, inside JSX. The underlying behaviour matches v-if: an element not returned is not mounted. React has no built-in equivalent of v-show; you would toggle a style or class yourself. Conditional rendering in React shows the other side.
What the video covers
The embed is Lesson 4 of Adam Jahr’s Composition API version of Vue Mastery’s Intro to Vue 3, written in <script setup>. It adds an “In Stock” / “Out of Stock” message to a product page with v-if and v-else, in about five minutes. The finished code for that lesson only uses those two directives, so v-else-if, the <template> grouping, the full v-if versus v-show trade-off and the v-for precedence rule are explained here rather than in the clip. When an element should animate in and out instead of popping, Transition wraps either directive.
Where this fits
Next is list rendering with v-for, the other directive that decides how many copies of an element exist.
Check yourself
A text input sits inside `<div v-if="open">`. A user types into it, `open` becomes false, then true again. Is the typed text still there? What changes with `v-show`?
With `v-if` the text is gone. Setting `open` to false removes the div and the input from the DOM, and setting it back to true creates a fresh input. With `v-show` the input is never removed, only hidden with `display: none`, so the typed text survives.
Why does this fail to compile: `<p v-if="a">A</p> <span>hi</span> <p v-else>B</p>`?
`v-else` has to be on the element directly after the `v-if` (or `v-else-if`) element. The `<span>` in between ends the chain, so the compiler finds a `v-else` with no matching `v-if` and reports an error.
A settings panel opens and closes dozens of times per session and contains a heavy chart component. Which directive fits better, and why?
`v-show`. It mounts the panel once and then only toggles CSS, so repeated toggling is cheap and the chart is not torn down and rebuilt each time. `v-if` would unmount and remount the chart on every toggle.
Why does `<li v-for="user in users" v-if="user.active">` throw an error about `user` in Vue 3?
When both directives are on the same element, Vue 3 evaluates `v-if` before `v-for`. At that point the loop variable `user` does not exist yet. Filter the list in a computed property, or move the `v-for` onto a wrapping `<template>` and keep `v-if` on the inner element.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.