Conditional and List Rendering

Loading concept...

🎭 Vue.js Rendering & Directives: The Magic Show

Imagine you’re a magician on stage. Your wand? Vue.js directives. Your trick? Making things appear, disappear, and multiply before your audience’s eyes!


🪄 The Story of the Magic Theater

You run a magical theater. Sometimes you need to:

  • Show or hide props on stage (Conditional Rendering)
  • Multiply your assistant into many copies (List Rendering)
  • Track each copy so they don’t get confused (Keys)

Let’s learn these magical tricks!


🎪 Act 1: Conditional Directives

What Are They?

Think of conditional directives like a light switch. You decide what appears on your webpage based on a YES or NO question.

Real Life Example:

  • Is it raining? → Show umbrella icon
  • Is the user logged in? → Show their profile picture
  • Is the cart empty? → Show “Your cart is empty” message

The v-if Magic Trick

v-if is like a magic door. If the condition is TRUE, the element appears. If FALSE, it completely vanishes—not just hidden, but GONE from the stage!

<div v-if="isHappy">
  😊 I'm so happy!
</div>

When isHappy is true → You see the happy face. When isHappy is false → The whole thing disappears from the page.

The v-else Partner

Every v-if can have a v-else partner—like a backup performer!

<div v-if="isSunny">
  ☀️ Let's go outside!
</div>
<div v-else>
  🌧️ Let's stay inside.
</div>

Rule: v-else must come RIGHT AFTER v-if. No other elements in between!

The v-else-if Middle Child

Sometimes you need more than two choices:

<div v-if="score >= 90">
  🏆 Amazing! You got an A!
</div>
<div v-else-if="score >= 70">
  ⭐ Good job! You got a B!
</div>
<div v-else-if="score >= 50">
  👍 Not bad! You got a C!
</div>
<div v-else>
  📚 Keep practicing!
</div>

🎭 Act 2: The v-show Directive

v-show vs v-if: What’s Different?

Remember our magic door (v-if)? It completely removes things.

v-show is different. It’s like an invisibility cloak. The element is still there, just hidden with CSS!

<div v-show="isVisible">
  👻 Now you see me...
</div>

When isVisible is false, Vue adds display: none but the element stays in the HTML.

When to Use Which?

Use v-if when… Use v-show when…
Thing rarely changes Thing toggles often
Heavy content to load Simple show/hide
Need complete removal Speed matters most

Simple Rule:

  • Toggle button that clicks a lot? → v-show
  • User login check at page load? → v-if

🎪 Act 3: The v-for Directive

What is v-for?

Imagine you have a box of crayons. Instead of writing out each crayon one by one, v-for lets you say: “For EACH crayon in my box, show it on the page!”

<ul>
  <li v-for="fruit in fruits">
    🍎 {{ fruit }}
  </li>
</ul>

If fruits = ['Apple', 'Banana', 'Cherry'], you get:

  • 🍎 Apple
  • 🍎 Banana
  • 🍎 Cherry

Getting the Index

Sometimes you want to know the position number:

<li v-for="(fruit, index) in fruits">
  {{ index + 1 }}. {{ fruit }}
</li>

Output:

  1. Apple
  2. Banana
  3. Cherry

🔑 Act 4: The Key Attribute in v-for

Why Keys Matter

Imagine you have three dancers on stage: Anna, Bob, and Carla. If Bob leaves, Vue needs to know which dancer left!

Without keys, Vue might get confused and think Carla is Bob. With keys, each dancer has a name tag.

<div v-for="dancer in dancers" :key="dancer.id">
  {{ dancer.name }}
</div>

The Golden Rule

ALWAYS use :key with v-for!

Use something unique like an id. Avoid using the array index as a key when items can be added, removed, or reordered.

<!-- ✅ Good: Unique ID -->
<li v-for="item in items" :key="item.id">

<!-- ⚠️ Careful: Index can cause issues -->
<li v-for="(item, index) in items" :key="index">

🎭 Act 5: v-for with Objects

Looping Through Objects

You can loop through an object’s properties too!

<div v-for="(value, key) in person">
  {{ key }}: {{ value }}
</div>

If person = { name: 'Alice', age: 25, city: 'Paris' }:

  • name: Alice
  • age: 25
  • city: Paris

Getting All Three: Value, Key, and Index

<div v-for="(value, key, index) in person">
  {{ index }}. {{ key }} = {{ value }}
</div>

Output:

    1. name = Alice
    1. age = 25
    1. city = Paris

🔢 Act 6: v-for with Ranges

Counting with v-for

Want to repeat something 5 times? Use a number!

<span v-for="n in 5" :key="n"></span>

This shows: ⭐⭐⭐⭐⭐

Note: n starts at 1, not 0!

Creating a Star Rating

<span v-for="n in rating" :key="n"></span>
<span v-for="n in (5 - rating)" :key="'empty' + n"></span>

If rating = 3: ⭐⭐⭐☆☆


🔄 Act 7: Array Change Detection

Vue’s Magic Watchfulness

Vue automatically watches your arrays! When you change them, the page updates.

Methods Vue Detects

These array methods trigger automatic updates:

Method What It Does
push() Adds items to end
pop() Removes last item
shift() Removes first item
unshift() Adds items to start
splice() Add/remove anywhere
sort() Reorder items
reverse() Flip the order
// All of these update the view automatically!
this.fruits.push('Mango')
this.fruits.pop()
this.fruits.splice(1, 1, 'Grape')

What Doesn’t Work?

Direct index assignment doesn’t trigger updates:

// ❌ Won't update the view
this.items[0] = 'New Value'

// ✅ Do this instead
this.items.splice(0, 1, 'New Value')

Changing array length directly won’t work:

// ❌ Won't update the view
this.items.length = 2

// ✅ Do this instead
this.items.splice(2)

🔍 Act 8: Displaying Filtered Lists

The Problem

What if you have 100 items but only want to show some of them?

Never modify the original array! Instead, use a computed property.

Using Computed Properties

data() {
  return {
    numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  }
},
computed: {
  evenNumbers() {
    return this.numbers.filter(n => n % 2 === 0)
  }
}
<li v-for="n in evenNumbers" :key="n">
  {{ n }}
</li>

Shows only: 2, 4, 6, 8, 10

Real Example: Search Filter

data() {
  return {
    searchQuery: '',
    users: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
      { id: 3, name: 'Charlie' }
    ]
  }
},
computed: {
  filteredUsers() {
    return this.users.filter(user =>
      user.name.toLowerCase()
        .includes(this.searchQuery.toLowerCase())
    )
  }
}

Using Methods Inside v-for

When computed properties can’t work (like nested loops), use methods:

<ul v-for="group in groups" :key="group.id">
  <li v-for="item in getActiveItems(group)"
      :key="item.id">
    {{ item.name }}
  </li>
</ul>
methods: {
  getActiveItems(group) {
    return group.items.filter(item => item.active)
  }
}

🎬 The Grand Finale: Quick Summary

graph LR A["Vue Rendering"] --> B["Conditional"] A --> C["List Rendering"] B --> D["v-if / v-else-if / v-else"] B --> E["v-show"] C --> F["v-for with Arrays"] C --> G["v-for with Objects"] C --> H["v-for with Ranges"] F --> I["Always use :key"] C --> J["Array Change Detection"] C --> K["Filtered Lists"]

🎯 Remember These Magic Words

  1. v-if = Complete removal (expensive toggle)
  2. v-show = CSS hiding (cheap toggle)
  3. v-for = Loop through anything
  4. :key = Give each item an ID tag
  5. Computed = Best way to filter lists

🌟 You Did It!

You’ve learned the magic of Vue.js rendering! Now you can:

  • ✅ Show and hide content conditionally
  • ✅ Choose between v-if and v-show wisely
  • ✅ Loop through arrays, objects, and numbers
  • ✅ Use keys to keep Vue happy
  • ✅ Detect array changes automatically
  • ✅ Filter lists like a pro

You’re now a Vue.js rendering magician! 🎩✨

Loading story...

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Interactive content is coming soon.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Cheatsheet is coming soon.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Quiz is coming soon.

Flashcard Preview

Flashcard - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Flashcards are coming soon.