Conditional and List Rendering with v-if, v-show, and v-for
Owner: SnippetBot
Created: 2026-09-20 00:00:23
Size: 2.04 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<template>
<div>
<h1>Conditional and List Rendering</h1>
<h2>v-if / v-else-if / v-else</h2>
<button @click="toggleVisibility">Toggle Content</button>
<div v-if="isVisible" style="background-color: lightgreen; padding: 10px; margin-top: 10px;">
<p>This content is visible because v-if is true.</p>
</div>
<div v-else-if="isError" style="background-color: lightcoral; padding: 10px; margin-top: 10px;">
<p>An error occurred! (v-else-if)</p>
</div>
<div v-else style="background-color: lightgray; padding: 10px; margin-top: 10px;">
<p>This content is visible because v-if is false. (v-else)</p>
</div>
<h2>v-show</h2>
<button @click="toggleDisplay">Toggle Display</button>
<div v-show="isDisplayed" style="background-color: lightblue; padding: 10px; margin-top: 10px;">
<p>This content uses v-show. It's always rendered but toggles display CSS property.</p>
</div>
<h2>v-for: List Rendering</h2>
<h3>Shopping List:</h3>
<ul>
<li v-for="(item, index) in shoppingList" :key="item.id">
{{ index + 1 }}. {{ item.name }} (Quantity: {{ item.qty }})
</li>
</ul>
<h3>Object Iteration:</h3>
<ul>
<li v-for="(value, key) in userInfo" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
const isVisible = ref(true);
const isError = ref(false); // Example for v-else-if
const isDisplayed = ref(true);
const toggleVisibility = () => {
isVisible.value = !isVisible.value;
if (!isVisible.value) {
// Simulate an error condition if visibility is off
isError.value = Math.random() > 0.5;
} else {
isError.value = false;
}
};
const toggleDisplay = () => {
isDisplayed.value = !isDisplayed.value;
};
const shoppingList = reactive([
{ id: 1, name: 'Apples', qty: 2 },
{ id: 2, name: 'Milk', qty: 1 },
{ id: 3, name: 'Bread', qty: 1 }
]);
const userInfo = reactive({
firstName: 'John',
lastName: 'Doe',
age: 30,
occupation: 'Developer'
});
</script>