Lists and keys
Render lists with v-for and stable keys.
What you will be able to do
- Use v-for with a stable id.
- Never use Math.random() as a key.
- Prefer an id over the index for mutable lists.
- Use a wrapper element with a key for fragments.
In plain English
v-for renders a template for every item. The key must be stable and unique so Vue can move DOM nodes instead of recreating them. Using the array index as a key causes bugs when items are inserted, removed or reordered.
<script setup>
const lessons = [
{ id: 1, title: 'HTML' },
{ id: 2, title: 'CSS' },
]
</script>
<template>
<ul>
<li v-for="lesson in lessons" :key="lesson.id">{{ lesson.title }}</li>
</ul>
</template>Your turn
EasyRender with an id key
Render an array of objects by title and use their id as the key.
HTML · starter
<li v-for="item in items">Check your understanding before moving on.
Knowledge checkQuestion 1
Why is a stable key important in v-for?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.