0
0
Vueframework~15 mins

v-for with index in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using v-for with index in Vue
📖 Scenario: You are building a simple Vue app that shows a list of fruits. You want to display each fruit with its position number in the list.
🎯 Goal: Create a Vue component that uses v-for to loop over a list of fruits and display each fruit's name along with its index number starting from 1.
📋 What You'll Learn
Create a reactive array called fruits using ref with the exact array: ['Apple', 'Banana', 'Cherry', 'Date']
Add a v-for directive to loop over fruits with variables fruit and index
Display the index number starting from 1 before each fruit name
Use a unique key attribute with the index in the v-for loop
💡 Why This Matters
🌍 Real World
Displaying lists with position numbers is common in apps like to-do lists, rankings, or menus.
💼 Career
Understanding v-for with index and keys is essential for building dynamic lists in Vue applications.
Progress0 / 4 steps
1
Create the fruits array
Import ref from 'vue' and create a reactive array called fruits using ref. It should contain these exact strings: 'Apple', 'Banana', 'Cherry', 'Date'.
Vue
Need a hint?

Use ref from Vue to create a reactive array called fruits.

2
Add the v-for loop with index
Inside the <div> in the template, add an unordered list <ul>. Inside it, add a list item <li> that uses v-for to loop over fruits with variables fruit and index. Use v-for="(fruit, index) in fruits".
Vue
Need a hint?

Use v-for="(fruit, index) in fruits" on the <li> and add :key="index".

3
Display the index and fruit name
Inside the <li> tag, display the index number plus 1, followed by a dot and a space, then the fruit name. Use mustache syntax like {{ index + 1 }}. {{ fruit }}.
Vue
Need a hint?

Use {{ index + 1 }}. {{ fruit }} inside the <li> to show the number and fruit.

4
Complete the Vue component
Make sure the Vue component has the full template with the v-for loop showing the index and fruit, and the fruits array defined in script setup using ref. The key attribute must be set to index on the <li>.
Vue
Need a hint?

Check that all parts are included: the fruits array, the v-for with fruit and index, the key, and the display of index plus 1 and fruit.