Positions and Numbers

v-for can give you a second value: the item's position in the array, its index. Write two names in parentheses, the item first and the index second:

<script setup>
const bestSellers = [
    { id: 2, name: "Cappuccino" },
    { id: 1, name: "Espresso" },
    { id: 5, name: "Carrot Cake" },
];
</script>

<template>
    <p v-for="(item, index) in bestSellers" :key="item.id">
        {{ index + 1 }}. {{ item.name }}
    </p>
</template>

The page shows:

1. Cappuccino
2. Espresso
3. Carrot Cake

The index counts from 0, as array indexes do, so for numbers that start at 1, show index + 1. The key stays item.id, even though the index is right there: as the previous exercise explained, an item's index changes when an item before it is removed.

v-for can also count. With a number instead of an array, it repeats the element that many times, and the name gets the numbers from 1, not 0, up to that number:

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

That's three cups: ☕☕☕. The numbers are different from each other, so they make good keys. The number can also come from your data: v-for="n in item.rating" repeats an element as many times as the item's rating says.

Instructions

  1. Number the items: put each item's position before its name, starting from 1, so that the list says 1. Espresso, 2. Cappuccino and so on.

  2. After each name, show as many stars ★ as the item's rating, each in a span of its own: use v-for with the number.