Episode 11 of 44

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

Featurev-ifv-show
When falseElement is removed from the DOMElement stays in the DOM with display: none
Toggle costHigher (destroy and recreate)Lower (just toggle CSS)
Initial renderSkipped if false (faster)Always rendered
Use whenCondition rarely changesToggling 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-if removes/adds the element from the DOM; v-show toggles display: none
  • Use v-if for conditions that rarely change; v-show for frequent toggling
  • v-else-if and v-else must follow v-if without interruption
  • <template> groups multiple elements for a single conditional without extra DOM nodes