Vue

Lesson 04

List rendering keys

Use stable item identifiers for v-for keys so Vue can preserve component and form state across list changes.

Good Code

ReviewQueue.vue
<script setup lang="ts">
defineProps<{
  reviews: Array<{ id: string; title: string; reviewer: string }>;
}>();

// Each key follows the review record when the list is sorted.
</script>

<template>
  <article v-for="review in reviews" :key="review.id">
    <h2>{{ review.title }}</h2>
    <p>{{ review.reviewer }}</p>
  </article>
</template>

Bad Code

ReviewQueue.vue
<script setup>
defineProps(["reviews"]);

// Index keys change meaning when rows move.
</script>

<template>
  <article v-for="(review, index) in reviews" :key="index">
    <h2>{{ review.title }}</h2>
    <input v-model="review.note">
  </article>
</template>

Review Notes

What to review

Good Code

The good version keys each row by the review id. Vue can keep row state attached to the same review after sorting or inserting.

Bad Code

The bad version keys rows by array index. Moving a row can attach input state or child component state to the wrong review.

Takeaways

  • A v-for key should identify the data item, not its current position in the array.