Consider the following Vue template snippet:
<ul>
<li v-for="(item, index) in items" :key="index">
{{ index }} - {{ item }}
</li>
</ul>If items is ["apple", "banana", "cherry"], what will be the rendered list items?
<ul> <li v-for="(item, index) in items" :key="index"> {{ index }} - {{ item }} </li> </ul>
Remember that index starts at 0 in v-for.
The v-for directive provides the current index starting at 0. So the output shows the index followed by the item.
Which of the following is the correct syntax to use v-for with both item and index in Vue?
Check the parentheses and order of variables.
The correct syntax uses parentheses around item, index followed by in items.
Given a list of items that may change order or content, which key binding is best to avoid rendering bugs?
<li v-for="(item, index) in items" :key="?">{{ item }}</li>Keys should uniquely identify items and remain stable.
Using a unique property like item.id is best. Using index can cause bugs if items reorder. Random keys cause unnecessary re-renders.
Consider this code:
<div v-for="(item, index) in items">
<p>{{ index }}: {{ item }}</p>
</div>Vue shows a warning about missing key. Which option fixes it correctly?
<div v-for="(item, index) in items">
<p>{{ index }}: {{ item }}</p>
</div>Keys must be on the element with v-for.
The key must be on the element that has the v-for directive, here the div. Adding it to p does not fix the warning.
What is the main problem when using the index as the key in a v-for loop for a list that can have items inserted or removed?
Think about how keys help Vue track elements.
Using index as key can cause Vue to reuse DOM elements wrongly when list items change order or are added/removed, leading to UI bugs like wrong data shown.