Vue 3·Vue from reactivity to a routed app

Lists and keys

Render lists with v-for and stable keys.

Intermediate 11 min read Lesson 5 of 300 Challenge included
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.

list.vueHTML
<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

Render with an id key

Easy

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Components and props
Lesson 5 of 300 · 0% of course