Vue.js Conditional Rendering

Conditional rendering lets you show or hide parts of your webpage based on data conditions. Instead of manually hiding elements with JavaScript, you tell Vue the condition, and Vue handles showing and hiding automatically.

The v-if Directive

v-if adds an element to the page when its condition is true and completely removes it from the DOM when the condition is false.

<div id="app">
  <p v-if="isLoggedIn">Welcome back, user!</p>
  <button @click="isLoggedIn = !isLoggedIn">Toggle Login</button>
</div>

<script>
  Vue.createApp({
    data() {
      return { isLoggedIn: false };
    }
  }).mount("#app");
</script>

Diagram: v-if Behavior

isLoggedIn = false:
┌──────────────────────────────┐
│ [Toggle Login]               │  ← paragraph does not exist in DOM
└──────────────────────────────┘

isLoggedIn = true:
┌──────────────────────────────┐
│ Welcome back, user!          │  ← paragraph is in the DOM
│ [Toggle Login]               │
└──────────────────────────────┘

v-else — The Alternative Block

v-else provides a fallback element that shows when the v-if condition is false. It must immediately follow the element that has v-if.

<div id="app">
  <p v-if="isLoggedIn">Welcome back!</p>
  <p v-else>Please log in to continue.</p>
</div>

Diagram: v-if and v-else

isLoggedIn = true    →  "Welcome back!"           shown
                        "Please log in..."        hidden

isLoggedIn = false   →  "Welcome back!"           hidden
                        "Please log in..."        shown

Only one is ever in the DOM at a time.

v-else-if — Multiple Conditions

v-else-if adds more conditions between v-if and v-else. Vue checks each condition in order and renders the first one that is true.

<div id="app">
  <p v-if="score >= 90">Grade: A — Excellent!</p>
  <p v-else-if="score >= 75">Grade: B — Good job!</p>
  <p v-else-if="score >= 60">Grade: C — You passed.</p>
  <p v-else>Grade: F — Please try again.</p>
</div>

<script>
  Vue.createApp({
    data() {
      return { score: 82 };
    }
  }).mount("#app");
</script>

Diagram: Grade Decision Tree

score = 82

score ≥ 90?  No  →  skip
score ≥ 75?  Yes →  show "Grade: B — Good job!"  ← renders this
score ≥ 60?  (not checked — first true already found)
v-else       (not rendered)

Grouping Multiple Elements with <template>

Sometimes you want to show or hide several elements together based on one condition. Wrapping them in individual v-ifs is repetitive. Instead, wrap them in a <template> tag with a single v-if. The <template> tag itself does not appear in the final HTML — only its contents do.

<template v-if="isAdmin">
  <h3>Admin Panel</h3>
  <p>You have full access to all settings.</p>
  <button>Manage Users</button>
</template>

Diagram: Template Tag Wrapper

isAdmin = true:
DOM contains:
  <h3>Admin Panel</h3>
  <p>You have full access...</p>
  <button>Manage Users</button>

isAdmin = false:
DOM contains: (nothing — the template tag leaves no trace)

The v-show Directive

v-show also shows or hides an element based on a condition. The difference from v-if is that v-show keeps the element in the DOM at all times — it just toggles the CSS display property.

<p v-show="isVisible">This text appears and disappears.</p>

Diagram: v-if vs v-show

Condition = true:
  v-if   →  Element IS in the DOM     (visible)
  v-show →  Element IS in the DOM     (display: block — visible)

Condition = false:
  v-if   →  Element NOT in the DOM    (completely removed)
  v-show →  Element IS in the DOM     (display: none — invisible)

When to Use v-if vs v-show

Comparison Table

┌─────────────────────┬──────────────────────┬──────────────────────┐
│ Feature             │ v-if                 │ v-show               │
├─────────────────────┼──────────────────────┼──────────────────────┤
│ DOM presence        │ Removed when false   │ Always in DOM        │
│ First render cost   │ Low (skips if false) │ Always renders       │
│ Toggle cost         │ Higher (add/remove)  │ Low (CSS only)       │
│ Use when            │ Condition rarely     │ Condition changes    │
│                     │ changes              │ frequently           │
│ Supports v-else     │ Yes                  │ No                   │
└─────────────────────┴──────────────────────┴──────────────────────┘

Use v-if for elements that rarely toggle — like an admin panel only shown to admins. Use v-show for elements that toggle frequently — like a dropdown menu or a tooltip.

Real-World Example: Shopping Cart Status

<div id="app">
  <h3>Your Cart</h3>

  <div v-if="cartItems.length === 0">
    <p>Your cart is empty. Start shopping!</p>
  </div>

  <div v-else>
    <p>You have {{ cartItems.length }} item(s) in your cart.</p>
    <p v-if="cartItems.length > 5">
      That's a big order! You qualify for free shipping.
    </p>
  </div>
</div>

<script>
  Vue.createApp({
    data() {
      return {
        cartItems: ["Notebook", "Pen", "Ruler", "Eraser", "Marker", "Stapler"]
      };
    }
  }).mount("#app");
</script>

Diagram: Cart State Flow

cartItems.length = 0:
  Shows: "Your cart is empty. Start shopping!"

cartItems.length = 3:
  Shows: "You have 3 item(s) in your cart."
  Hides: Free shipping message (3 is not > 5)

cartItems.length = 6:
  Shows: "You have 6 item(s) in your cart."
  Shows: "That's a big order! You qualify for free shipping."

Conditional Rendering with Computed Values

You can use computed properties or method return values inside v-if conditions instead of inline expressions.

<div id="app">
  <p v-if="isWeekend">Enjoy your weekend!</p>
  <p v-else>Have a productive workday!</p>
</div>

<script>
  Vue.createApp({
    data() {
      return { today: new Date().getDay() };
    },
    computed: {
      isWeekend() {
        return this.today === 0 || this.today === 6;
      }
    }
  }).mount("#app");
</script>

This keeps the template clean. The logic lives in the computed property, not inside the HTML.

Summary

v-if, v-else-if, and v-else work together to control which elements Vue adds to the DOM. Use a <template> wrapper to apply one condition to a group of elements. v-show is the fast-toggle alternative that keeps elements in the DOM but hides them with CSS. Choose v-if for rare toggles and v-show for frequent ones. Both directives accept any JavaScript expression that evaluates to true or false.

Leave a Comment

Your email address will not be published. Required fields are marked *