Conditionals
Show and hide elements with v-if, v-else-if, v-else, and v-show — conditionally render parts of the template based on data.
Conditionals
Vue provides directives to conditionally render elements. If a condition is true, the element is shown; if false, it is hidden or removed from the DOM entirely.
v-if, v-else-if, v-else
<div id="app">
<p v-if="role === 'admin'">You are an admin</p>
<p v-else-if="role === 'moderator'">You are a moderator</p>
<p v-else>You are a regular user</p>
</div>
data: {
role: 'admin'
}
v-if vs v-show
| Feature | v-if | v-show |
|---|---|---|
| When false | Element is removed from the DOM | Element stays in the DOM with display: none |
| Toggle cost | Higher (destroy and recreate) | Lower (just toggle CSS) |
| Initial render | Skipped if false (faster) | Always rendered |
| Use when | Condition rarely changes | Toggling frequently |
v-show
<p v-show="showMessage">This message can be toggled</p>
<button @click="showMessage = !showMessage">Toggle</button>
v-show always renders the element but toggles its display CSS property. It is more efficient for elements that toggle frequently because it avoids the cost of destroying and recreating DOM elements.
Conditional Groups with template
<template v-if="loggedIn">
<h2>Welcome back!</h2>
<p>Your dashboard is ready.</p>
<button>View Profile</button>
</template>
The <template> element acts as an invisible wrapper — it groups elements for a conditional without adding an extra DOM node.
Key Takeaways
v-ifremoves/adds the element from the DOM;v-showtogglesdisplay: none- Use
v-iffor conditions that rarely change;v-showfor frequent toggling v-else-ifandv-elsemust followv-ifwithout interruption<template>groups multiple elements for a single conditional without extra DOM nodes