0
0
Vueframework~30 mins

Key attribute and why it matters in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Key Attribute in Vue
📖 Scenario: You are building a simple Vue app that shows a list of fruits. You want to understand how Vue uses the key attribute to keep track of each fruit when the list changes.
🎯 Goal: Create a Vue component that renders a list of fruits using v-for. Add a key attribute to each list item to help Vue track them efficiently.
📋 What You'll Learn
Create a list of fruits as an array of objects with id and name properties
Add a variable to hold the selected fruit's id
Use v-for to loop over the fruits and render each fruit's name in a list item
Add a key attribute to each list item using the fruit's id
Add a click event to each list item to update the selected fruit's id
💡 Why This Matters
🌍 Real World
Lists of items are common in web apps, like menus, product lists, or messages. Using keys helps Vue update only what changed, making apps faster and smoother.
💼 Career
Understanding keys is essential for frontend developers working with Vue to build efficient, bug-free user interfaces.
Progress0 / 4 steps
1
Create the fruits data array
Create a fruits array in the setup function with these exact objects: { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' }.
Vue
Need a hint?

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

2
Add a selectedFruitId variable
Add a selectedFruitId variable using ref and set its initial value to null inside the setup function.
Vue
Need a hint?

Use ref(null) to create a reactive variable called selectedFruitId.

3
Render the fruits list with v-for and key
Inside the <ul> tag, use v-for to loop over fruits with variables fruit and index. Render each fruit's name inside a <li>. Add a :key attribute to each <li> using fruit.id.
Vue
Need a hint?

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

4
Add click event to update selectedFruitId
Add a @click event to each <li> that sets selectedFruitId.value to fruit.id. Also, add a class binding that adds the class selected when fruit.id === selectedFruitId.value.
Vue
Need a hint?

Use @click="selectedFruitId.value = fruit.id" and bind class with :class="{ selected: fruit.id === selectedFruitId.value }".