Mrs. Sri's stall has three dishes: Fried Rice, Chicken Noodles, Iced Tea. Tomorrow it might be ten. Writing <li> ten times, then editing it again for every new dish, is not a fun plan.
Mrs. Sri doesn't write her menu cards one by one either. She has one card stamp, and she stamps it once for every line in her menu notebook. Add a line to the notebook, and a new card appears. In Vue, that stamp is v-for: a directive that repeats one element for every item in an array. The element that carries v-for is the picture on the stamp, and the array is the notebook. So that Mrs. Sri knows which card to take down when a dish is sold out, each card gets a name tag. In Vue, that name tag is :key.
v-for: one element per item
Here is a menu list made with v-for:
const menu = ref([
{ id: 1, name: "Fried Rice", price: 15 },
{ id: 2, name: "Chicken Noodles", price: 12 },
{ id: 3, name: "Iced Tea", price: 5 },
])
---template---
<ul>
<li v-for="m in menu" :key="m.id">{{ m.name }}: ${{ m.price }}</li>
</ul>
The HTML that Vue makes:
<ul>
<li>Fried Rice: $15</li>
<li>Chicken Noodles: $12</li>
<li>Iced Tea: $5</li>
</ul>
v-for="m in menu"means "for every item inmenu, call that itemm". The name is up to you, andmonly exists inside that element.- The directive goes on the element that repeats, here the
<li>, not on its wrapper, the<ul>. :key="m.id"gives every<li>a unique name tag. The reason is in the "Why :key matters" section below.- The array is reactive.
menu.value.push({ id: 4, name: "Sweet Tea", price: 4 })in the script adds a<li>right away. - In the first exercise, the array holds text:
const fruits = ref(["Apple", "Mango", "Orange"])and<li v-for="item in fruits" :key="item">{{ item }}</li>. Each text in that array is different, so the text itself can be the key. The<li>holds only{{ item }}: the checker refuses an<li>whose content is typed in directly.
Position numbers: (item, index)
With the same menu in the script, this template shows position numbers:
---template---
<ul>
<li v-for="(m, i) in menu" :key="m.id">{{ i + 1 }}. {{ m.name }}</li>
</ul>
i |
What shows |
|---|---|
| 0 | 1. Fried Rice |
| 1 | 2. Chicken Noodles |
| 2 | 3. Iced Tea |
- The second name inside the parentheses is the index: the item's position in the array, starting at 0. That's why the number is written
i + 1. - If an item is an object, show its properties. In the second exercise,
studentsholds{ name: "Ani" },{ name: "Budi" },{ name: "Cici" }. Each entry is written<li v-for="(s, index) in students" :key="index">{{ s.name }}</li>, inside<ol id="list">. An<ol>numbers itself, soindexis only used as the key. That list never changes, so the index is safe here.
v-for over an object and a number
v-for can also repeat over the contents of an object, or repeat as many times as a number:
const order = reactive({ menu: "Fried Rice", count: 2, note: "spicy" })
---template---
<ul>
<li v-for="(value, key, i) in order" :key="key">{{ i }}. {{ key }}: {{ value }}</li>
</ul>
<button v-for="n in 3" :key="n">Table {{ n }}</button>
| What's written | The result |
|---|---|
(value, key, i) in order |
0. menu: Fried Rice, 1. count: 2, 2. note: spicy |
n in 3 |
buttons Table 1, Table 2, Table 3 |
- For an object, the first name (
value) holds the property's value, the second name (key) holds the property's name, and the third name (i) holds the index. No two properties in one object have the same name, so:key="key"uses the property name as the key. n in 3repeats three times, and starts at 1, not 0.
Why :key matters
In this code, each menu row has a note input and a Sold out button. The function remove takes the id of a dish and removes that dish from the array. The key uses the index, :key="i":
const menu = ref([
{ id: 1, name: "Fried Rice" },
{ id: 2, name: "Chicken Noodles" },
{ id: 3, name: "Iced Tea" },
])
function remove(id) {
menu.value = menu.value.filter((m) => m.id !== id)
}
---template---
<ul>
<li v-for="(m, i) in menu" :key="i">
{{ m.name }} <input placeholder="note" />
<button @click="remove(m.id)">Sold out</button>
</li>
</ul>
Guess before you look at the table: you type "spicy" into the Fried Rice row's input, then click Sold out on that row. Which row holds "spicy" now?
| Step | With :key="i" |
With :key="m.id" |
|---|---|---|
| Type "spicy" in the Fried Rice row | Fried Rice [spicy], Chicken Noodles [ ], Iced Tea [ ] | the same |
| Click Sold out on the Fried Rice row | Chicken Noodles [spicy], Iced Tea [ ] | Chicken Noodles [ ], Iced Tea [ ] |
With :key="i", "spicy" moves to Chicken Noodles. This is what happens:
- Fried Rice is removed, so Chicken Noodles moves to position 0. Its key is now 0, the same key the Fried Rice row had.
- Vue sees that the row with key 0 is still there, so Vue reuses the old
<li>with key 0 (the Fried Rice one) and only swaps its text. - What you type into an input is kept by the element, not by the data, so "spicy" stays behind in that
<li>. - The one thrown away is the last
<li>, with key 2.
With :key="m.id", Vue sees key 1 is gone and throws away the Fried Rice <li> together with its input.
- A key must be unique and stay the same for the same item: usually an id from the data.
- The index is only safe for a list whose items are never removed, inserted, or reordered.
- With no
:keyat all, Vue matches rows by order, the same as:key="i". The browser gives no warning of any kind. What flags it is Vue's official ESLint plugin (vue/require-v-for-key), a tool that checks code before it runs.
📌 v-for and v-if on the same element
This code puts v-for and v-if on the same <li>, to show the dishes that are still in stock (say each item in menu has a stock property):
---template---
<ul>
<li v-for="m in menu" v-if="m.stock > 0" :key="m.id">{{ m.name }}</li>
</ul>
In Vue 3, v-if runs before v-for, when m doesn't exist yet. The render stops with TypeError: Cannot read properties of undefined (reading 'stock'), and the whole component doesn't show. In development mode, the console also writes [Vue warn]: Property "m" was accessed during render but is not defined on instance. The fix is to filter the list first with a computed:
const available = computed(() => menu.value.filter((m) => m.stock > 0))
// template: <li v-for="m in available" :key="m.id">{{ m.name }}</li>
available holds only the dishes whose stock is more than 0, and v-for repeats over available. Another way: move the v-for to <template v-for="m in menu" :key="m.id"> and put <li v-if="m.stock > 0"> inside it.
⚠️ Rows that swap, multiply, or won't update
- The index as key on a list that changes. Typed text, focus or animation stays behind on the wrong row. Use an id from the data.
v-foron the wrapper.<ul v-for="item in fruits">makes three<ul>s, each holding one<li>. Putv-foron the<li>.- Typing the content in. Three
<li>s typed in directly, like<li>Apple</li>, look the same as thev-forresult, but don't change when the data changes. In the exercise, the checker refuses an<li>whose content starts with a letter, so the content is just{{ item }}. v-ifandv-foron one element.v-ifruns first, when the item doesn't exist yet. Filter with a computed, or use<template v-for>.
TL;DR: v-for is a directive that repeats one element for each item in an array. <li v-for="m in menu" :key="m.id">{{ m.name }}</li> makes one <li> per item in menu, and calls each item m. The directive goes on the element that repeats. (m, i) in menu gives an index (the item's position) starting at 0, (value, key, i) in object loops over an object's properties, and n in 3 gives 1, 2, 3. :key is each row's name tag: it must be unique and stay the same, usually an id from the data. With the index as key, removing a row makes the typed text in an input move to the next row, because Vue reuses elements by their key. Vue's official ESLint plugin (a code checking tool) flags a v-for without :key as a mistake. A v-if on the same element runs first, so filter the list with a computed first.
⚡ v-for: one element per item
Write:
const menu = ref([
{ id: 1, name: "Fried Rice", price: 15 },
{ id: 2, name: "Chicken Noodles", price: 12 },
{ id: 3, name: "Iced Tea", price: 5 },
])
---template---
<ul>
<li v-for="m in menu" :key="m.id">{{ m.name }}: ${{ m.price }}</li>
</ul>
Meaning: v-for is a directive (a special Vue attribute) that repeats one element for each item in an array. v-for="m in menu" means "for every item in menu, call that item m". The result is three <li>s. The directive goes on the element that repeats, the <li>, not on its wrapper <ul>. :key="m.id" gives every <li> a unique name tag.
⚡ :key is each row's name tag
Guess first: each menu row has a note input and a Sold out button, which removes that dish from the array. The key is the index, which is the item's position, starting at 0: :key="i". You type "spicy" into the Fried Rice row's input, then click Sold out on that row. Which row holds "spicy" now?
It moves to Chicken Noodles. Chicken Noodles now sits at position 0, so its key is the one Fried Rice had. That's why Vue reuses the old Fried Rice <li>, together with the text typed in its input.
Meaning: A key must be unique and stay the same for the same item, usually an id from the data: :key="m.id". The index is only safe for a list whose items are never removed, inserted, or reordered.
⚡ Filter first, then loop
Write:
const available = computed(() => menu.value.filter((m) => m.stock > 0))
// template: <li v-for="m in available" :key="m.id">{{ m.name }}</li>
Meaning: When v-if and v-for sit on the same element, Vue 3 runs v-if before v-for, while m doesn't exist yet. The render stops with a TypeError. So filter the list first with a computed: available holds only the dishes whose stock is more than 0, and v-for repeats over available.