Lists with v-for
In the JavaScript course, you drew a list from an array with a loop: for each item createElement(), textContent and append(), and before all that, you cleared the list. In Vue, you write the element once, with the directive v-for, and Vue makes one for each item of the array:
<script setup>
const menu = [
{ id: 1, name: "Espresso", price: 2 },
{ id: 2, name: "Cappuccino", price: 3 },
{ id: 3, name: "Green Tea", price: 3 },
];
</script>
<template>
<ul>
<li v-for="item in menu" :key="item.id">{{ item.name }}: €{{ item.price }}</li>
</ul>
</template>The page gets:
<ul>
<li>Espresso: €2</li>
<li>Cappuccino: €3</li>
<li>Green Tea: €3</li>
</ul>item in menu works like for (const item of menu): item is one element of the array after another, and you choose its name. Inside the element with v-for, in its text and in its attributes, item is the item that this element is for.
:key gives each element a key, a value that's different for each item. When the array changes, Vue compares the keys to find out which element belongs to which item, and then it adds, moves or removes only the elements of the items that changed. So the key has to stay with its item: use the item's id, not its position in the array. When an item is removed, the items after it move up a place. With positions as keys, Vue would think the last item was gone, and whatever is in the elements themselves, such as text typed into a field in one of them, would stay where it was and end up next to the wrong item. Always give v-for a :key.
When the array is in a ref, the list follows it: push() an item, and Vue adds an element for it. You don't clear or redraw anything.
Instructions
- 1
Inside
<ul class="menu">, show anlifor each item ofmenu, with its name and price:Espresso: €2. - 2
Give each
lia key::key="item.id"(with your name for the item instead ofitem, if you chose another one). The page looks the same, but now Vue can tell the items apart. - 3
Add a button Order to each item, which adds the item's name to
order. Write a functionaddToOrder(item)for it, and pass it the item:@click="addToOrder(item)".