Consider the following Vue 3 template snippet using v-for:
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>Given the data:
items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]What will be the rendered HTML inside the <ul>?
<ul> <li v-for="item in items" :key="item.id">{{ item.name }}</li> </ul>
Remember that v-for repeats the element for each item in the list, and {{ item.name }} outputs the name property.
The v-for directive loops over each object in the items array. For each object, it creates an <li> element showing the name property. So the list items are Apple, Banana, and Cherry.
v-for with index?In Vue 3, you want to render a list of names with their index number. Which of the following v-for syntaxes is correct?
Remember the syntax for v-for with index is (item, index) in list.
The correct syntax for v-for with index is (item, index) in list. Option D follows this pattern correctly.
v-for cause a warning?Look at this Vue 3 template snippet:
<div v-for="item in items">
{{ item.text }}
</div>Given items is an array of objects, Vue shows a warning about missing key. Why?
<div v-for="item in items">
{{ item.text }}
</div>Vue requires a special attribute on elements inside v-for loops to help with updates.
Vue requires a unique :key attribute on elements inside v-for loops. This helps Vue identify each element when the list changes, improving performance and avoiding rendering bugs. Without it, Vue shows a warning.
selected after clicking the second item?Given this Vue 3 component snippet:
<template>
<ul>
<li v-for="(item, idx) in items" :key="item.id" @click="selected = idx">
{{ item.name }}
</li>
</ul>
<p>Selected: {{ selected }}</p>
</template>
<script setup>
import { ref } from 'vue'
const items = [
{ id: 1, name: 'Red' },
{ id: 2, name: 'Green' },
{ id: 3, name: 'Blue' }
]
const selected = ref(null)
</script>If the user clicks the second list item (Green), what will be displayed in the <p>Selected:</p> paragraph?
The click sets selected to the index of the clicked item.
The @click handler sets selected to the index idx of the clicked item. The second item has index 1 (zero-based), so selected becomes 1.
:key in v-for discouraged?In Vue 3, you can use :key to help Vue track list items. Why is it generally discouraged to use the array index as the key?
Think about what happens if the list changes order but keys stay the same.
Using the array index as the key can cause Vue to reuse DOM elements incorrectly when the list changes order or items are inserted/removed. This can lead to bugs like wrong item updates or lost input focus. It's better to use a unique identifier from the data.