0
0
Vueframework~10 mins

v-for with index in Vue - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - v-for with index
Start with array
v-for loop begins
For each item in array
Assign index to variable
Render item and index
Move to next item
End if done
The v-for directive loops over an array, assigning each item and its index to variables, then renders them one by one.
Execution Sample
Vue
<ul>
  <li v-for="(item, index) in items" :key="index">
    {{ index }} - {{ item }}
  </li>
</ul>
This code loops over 'items' array and displays each item with its index in a list.
Execution Table
StepIndexItemActionRendered Output
10"Apple"Render first item with index 0<li>0 - Apple</li>
21"Banana"Render second item with index 1<li>1 - Banana</li>
32"Cherry"Render third item with index 2<li>2 - Cherry</li>
4--No more items, loop endsLoop ends
💡 Loop ends after all items in 'items' array are rendered.
Variable Tracker
VariableStartAfter 1After 2After 3Final
index-012-
item-"Apple""Banana""Cherry"-
Key Moments - 3 Insights
Why does the index start at 0 instead of 1?
In the execution_table rows 1-3, index starts at 0 because arrays in JavaScript and Vue are zero-based, meaning counting begins from zero.
What happens if we omit the index variable in v-for?
If index is omitted, you cannot display or use the position of the item in the list, as shown in execution_table where index is used to render output.
Why do we use :key with index in v-for?
The :key helps Vue track each item uniquely for efficient updates. Using index as key is shown in the code sample and is important for rendering performance.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the item at step 2?
A"Apple"
B"Banana"
C"Cherry"
Dundefined
💡 Hint
Check the 'Item' column in execution_table row with Step '2'.
At which step does the loop end according to the execution_table?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the 'Action' column where it says 'No more items, loop ends'.
If the items array had 4 elements, how many steps would the execution_table show?
A5 steps
B4 steps
C3 steps
D6 steps
💡 Hint
Notice the last step is for loop ending after all items are rendered.
Concept Snapshot
v-for with index syntax:
<li v-for="(item, index) in items" :key="index">{{ index }} - {{ item }}</li>

Loops over array 'items', assigns each element to 'item' and its position to 'index'.
Index starts at 0.
Use :key for efficient rendering.
Displays both index and item in the template.
Full Transcript
The v-for directive in Vue loops over an array. For each element, it assigns the element to a variable and its position to an index variable. The index starts at zero because arrays are zero-based. The loop renders each item with its index. The :key attribute helps Vue track each item uniquely for efficient updates. The loop ends after all items are rendered.