Blog>
Snippets

List rendering and keys with Vue 3

Show how to render a list of items using v-for and the importance of key attribute for tracking item identity in VDOM.
<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.text }}
    </li>
  </ul>
</template>

<script>
import { defineComponent, reactive } from 'vue';

export default defineComponent({
  name: 'ItemList',
  setup() {
    // This is reactive state for the component.
    const items = reactive([
      { id: 1, text: 'Learn JavaScript' },
      { id: 2, text: 'Learn Vue' },
      { id: 3, text: 'Build something awesome' }
    ]);

    // Exposed to the template
    return { items };
  }
});
</script>

<style>
ul {
  list-style-type: none;
  padding: 0;
}

li {
  padding: 8px;
  margin: 5px;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style>
This Vue component uses the v-for directive to iterate over an array of items and render them as a list in the template. Each list item has a unique key bound to item.id, which is important for Vue's reactivity system to track each item's identity when the list changes. The reactive() function from Vue 3's Composition API is used to make the items array reactive. CSS styles are applied for better presentation of the list.