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.
Lesson 04
Use stable item identifiers for v-for keys so Vue can preserve component and form state across list changes.
<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><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>The good version keys each row by the review id. Vue can keep row state attached to the same review after sorting or inserting.
The bad version keys rows by array index. Moving a row can attach input state or child component state to the wrong review.