Vue3 Fundamentals · Rendering & Templates

Keys in v-for

Keys in v-for

A list can change: an item is added, removed, or moved. When Vue updates the list it needs to know which rendered element belongs to which item, or it may reuse the wrong one and carry over stale state.

You tell Vue with the key attribute, bound to a value that identifies the item:

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

The key must be unique among the item's siblings and stable across renders, so Vue can match an element to its item between updates. An item's id is the usual choice. For a list of unique strings, the string itself works.

Avoid the array index as the key when the list can reorder: the index changes with position, so Vue loses track of which element is which and may reuse the wrong DOM node.

Your job is to render a keyed list of objects.

Challenge

The list prints each object instead of its name, and gives Vue no way to track the rows. Export an App component from App.vue that renders one <li> per item showing item.name, keyed by item.id.

The Test mounts your component and reads the list item texts. The starter renders the raw objects, so the Test fails — repeat the <li> with v-for and a :key.

App.vue
<script setup>
const items = [
  { id: 1, name: 'Ada' },
  { id: 2, name: 'Grace' },
  { id: 3, name: 'Alan' },
];
</script>

<template>
  <ul>
    <li v-for="item in items">{{ item }}</li>
  </ul>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.