Conditional Rendering — v-if and v-show
A new Shelf user has no books, so instead of an empty list they should see "Your shelf is empty — add your first book." Meanwhile the filter panel opens and closes every few seconds as people browse. Both are "show this sometimes", but they deserve different tools.
The rule
v-if builds or destroys; v-show only hides.
v-if renders an element only while its expression is truthy. When the expression turns falsy, the element, and any components inside it, are removed from the page entirely. Branches chain with v-else-if and v-else, which must sit on the element immediately after:
<p v-if="books.length === 0">Your shelf is empty — add your first book.</p>
<p v-else-if="books.length === 1">One book so far. Nice start.</p>
<BookList v-else :books="books" />To switch a group of elements without adding a wrapper, put v-if on a <template> tag; the template itself is not rendered:
<template v-if="showStats">
<h3>Stats</h3>
<p>{{ finishedCount }} finished</p>
</template>v-show always renders the element and toggles the CSS display property:
<aside v-show="filtersOpen" class="filters">...</aside>Three limits of v-show: it cannot be used on <template>, it has no v-else partner, and the hidden element still exists in the page, so its components are created and keep running.
Cost trade-off. v-if is lazy: if the condition starts false, nothing is built. But every toggle tears down and rebuilds. v-show pays once, up front, then toggling is nearly free.
The shortcut
Ask "How often will this flip?" Rarely, or often false from the start → v-if. Many times while the user is on the page → v-show. Need an else branch → v-if.
Empty-shelf message
Shown once for new users, never flips back and forth, needs an else (the list).
v-if/v-else.
A classic bug is slipping another element between a v-if and its v-else. The v-else then has no partner and Vue raises a compile error.
Drills
Answer fast — trust the rule.
What happens to an element with v-show when its condition is false?
Where must v-else be placed?
A settings drawer is opened and closed dozens of times per visit. Which fits best?
Which of these does NOT work?
Remember
v-if/v-else-if/v-elseadd and remove elements;v-showkeeps them and togglesdisplay.- Shortcut: flips often →
v-show; rarely, or needs an else →v-if. - Trap: anything between
v-ifandv-elsebreaks the chain;v-showdoes not work on<template>.
