LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 917 min read

Core Directives (v-if, v-for, v-show)

Control what renders and how many times using v-if, v-else, v-show, and v-for.

Conditional Rendering: v-if / v-else

v-if adds or removes an element from the DOM entirely, based on whether its expression is truthy. Pair it with v-else-if and v-else for multiple branches.

<template>
<p v-if="status === 'loading'">Loading…</p>
<p v-else-if="status === 'error'">Something went wrong.</p>
<p v-else>Here\'s your data!</p>
</template>

v-show

v-show keeps the element in the DOM always, and simply toggles its CSS display property. It never adds or removes anything from the DOM structure.

<template>
<p v-show="isVisible">This toggles with CSS, not DOM removal.</p>
</template>

v-if vs v-show

v-ifv-show
Toggle mechanismAdds/removes from the DOMToggles CSS display
Initial render costCheaper if condition starts falseAlways renders, even if hidden
Toggle costMore expensive per toggleCheaper per toggle
Best forRarely-changing conditionsFrequently toggled visibility

Rendering Lists: v-for

v-for repeats an element once per item in an array (or object), following an "item in items" syntax borrowed from JavaScript's for...in loops.

<script setup>
const fruits = ['Apple', 'Banana', 'Cherry'];
</script>
<template>
<ul>
<li v-for="(fruit, index) in fruits" :key="fruit">
{{ index }}: {{ fruit }}
</li>
</ul>
</template>

The key Attribute

Vue uses the :key attribute to track which DOM node corresponds to which array item across re-renders — this lets it correctly reuse, reorder, or remove elements instead of guessing based on position.

Always Use a Stable, Unique key

A unique ID from your data (like an item's id field) is the right key — using the array index works for static lists but breaks reordering, insertion, and deletion for dynamic ones.

Common Beginner Mistakes

Using v-if and v-for on the same element

Vue evaluates them together on one element in a way that's easy to get wrong — wrap the v-for element in a parent with v-if instead, or filter the array beforehand.

Forgetting :key entirely

Vue will warn about this — without a key, list updates can behave unpredictably, especially when items are added, removed, or reordered.

FAQs

Yes — v-for="(value, key) in object" iterates over an object's properties.

No — only v-if works on a <template> tag (to group multiple elements under one condition without an extra wrapper); v-show requires a single real element to toggle its display style on.

Summary

v-if/v-show control whether and how something renders, and v-for repeats an element per item in a list, tracked by :key. Next, you'll handle user interaction with event listeners.

Next Lesson →

Event Handling