0
0
Vueframework~30 mins

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

Choose your learning style9 modes available
Using v-for to Loop Over Objects in Vue
📖 Scenario: You are building a simple Vue app that shows a list of fruits and their colors. The data is stored as an object where each fruit name is a key and its color is the value.
🎯 Goal: Create a Vue component that uses v-for to loop over the fruit-color object and display each fruit with its color in a list.
📋 What You'll Learn
Create a Vue component with a data object called fruits containing fruit-color pairs
Add a variable called fruitKeys that holds the keys of the fruits object
Use v-for with fruitKeys to loop over the fruits and display each fruit and its color
Add a unique :key binding for each list item using the fruit name
💡 Why This Matters
🌍 Real World
Looping over objects is common when you have data stored as key-value pairs, like user settings or product details, and want to display them in a list.
💼 Career
Understanding how to use v-for with objects is essential for Vue developers to efficiently render dynamic lists from object data.
Progress0 / 4 steps
1
Create the fruits object
In the Vue component's setup script, create a constant called fruits that is an object with these exact entries: apple: 'red', banana: 'yellow', grape: 'purple'.
Vue
Need a hint?

Use const fruits = { apple: 'red', banana: 'yellow', grape: 'purple' } inside the <script setup> block.

2
Create fruitKeys array from fruits object
Add a constant called fruitKeys inside the <script setup> block that stores the keys of the fruits object using Object.keys(fruits).
Vue
Need a hint?

Use const fruitKeys = Object.keys(fruits) to get the keys from the fruits object.

3
Use v-for to loop over fruitKeys and display fruit and color
Inside the <template>, add a <li> element inside the <ul> that uses v-for="fruit in fruitKeys" to loop over fruitKeys. Inside each <li>, display the fruit name and its color from fruits[fruit].
Vue
Need a hint?

Use <li v-for="fruit in fruitKeys" :key="fruit">{{ fruit }} is {{ fruits[fruit] }}</li> inside the <ul>.

4
Add accessibility and finalize the list
Add an aria-label attribute with the value Fruit colors list to the <ul> element to improve accessibility.
Vue
Need a hint?

Add aria-label="Fruit colors list" to the <ul> tag for screen readers.