← Back to Vue.js Course | Chapter 2: Template Syntax | Lesson 7 of 7

Key attribute

The key attribute gives each list item a stable identity so Vue can update lists correctly and efficiently.

In this page:

  1. Key attribute
Syntax
markup
<li v-for="item in items" :key="item.id">{{ item.name }}</li>

Key attribute

When a list changes, Vue reuses elements in place unless keys tell it which item is which. Stable, unique keys let Vue move, add and remove the right elements and keep component or input state attached to the correct item.

Changing a key forces Vue to recreate the element.

Note: Changing an element's key is a way to force it to re-render from scratch.

Example: Key attribute

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <button @click="shuffle">Reverse</button>
  <ul>
    <li v-for="t in todos" :key="t.id"><input :value="t.text"> {{ t.id }}</li>
  </ul>
</div>
<script>
  Vue.createApp({
    data() { return { todos: [{ id: 1, text: "milk" }, { id: 2, text: "eggs" }, { id: 3, text: "tea" }] }; },
    methods: { shuffle() { this.todos.reverse(); } },
  }).mount("#app");
  console.log("before:", [...document.querySelectorAll("li")].map((li) => li.textContent.trim()));
  document.querySelector("button").click();
  Vue.nextTick(() => console.log("after:", [...document.querySelectorAll("li")].map((li) => li.textContent.trim())));
</script>
</body>
</html>

<!-- Output:
Rendered: Reverse 3 2 1
console: before: 1,2,3
console: after: 3,2,1
-->
Live Example
Related Topics
Common Mistakes
  1. Using index as key on reorderable lists
  2. Using non-unique keys
  3. Using objects as keys
Chapter Summary
  • Keys identify list items
  • They must be unique and stable
  • Wrong keys mix up element state
  • A new key recreates the element
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.