🎓 A1Learner
🔍
0 of 50 lessons completed

List Keys

A list key is a value that marks one row as one item. Vue uses the key to tell rows apart when a list changes.

Add a key

Each row carries the id of its fruit.

<li v-for="fruit in fruits" :key="fruit.id">{{ fruit.name }}</li>

Ids stay with items

Each object holds its own id.

const fruits = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' }
])

Keys work for people too

Each person row carries that person id.

<li v-for="person in people" :key="person.id">{{ person.name }}</li>

Example

<script setup>
import { ref } from 'vue'
const fruits = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Cherry' }
])
const people = ref([
  { id: 1, name: 'Ada' },
  { id: 2, name: 'Ben' }
])
</script>
<template>
  <div>
    <ul>
      <li v-for="fruit in fruits" :key="fruit.id">{{ fruit.name }}</li>
    </ul>
    <p>{{ fruits.length }} fruits</p>
  </div>
</template>

Key points

  • :key is a binding that gives each repeated row its own key.
  • A good key is a value that stays with the item, like an id.
  • An id is a short number that names one item, and it never changes.
  • Vue matches each row to its item by the key when items move or leave the list.
  • Without a key, Vue can reuse the wrong row, so a box can keep the wrong text.
  • The key goes on the same tag as v-for, like :key="fruit.id".

In this example, fruits is a ref that holds three objects. people is a ref that holds two objects. Each object holds an id and a name. Each row carries :key with the id of its fruit. The key never shows on the page. The paragraph shows the count of fruits, and it reads 3 fruits. When the list changes, Vue uses each key to match each row to its fruit.

Note

A list position is a weak key, so use an id when the list can change order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does each row in a list need a :key?