Vue.js course · Module 2: Template Syntax

List Rendering with v-for

6 min read ·
In this lesson5

Just as the NOVA base displays data from multiple sensors simultaneously, v-for renders a list of elements.

The station has dozens of sensors, and their number keeps changing: technicians install new ones and remove broken ones. Copying an <li> tag by hand for every sensor is out of the question, because the template would need fixing after every hardware change. The v-for directive repeats an element for each item in the data, and when the data changes, the list in the hologram changes with it.

Basic v-for

The syntax resembles a JavaScript loop: in v-for="sensor in sensors" the word sensor is an alias for the current item, and sensors is the source array. Writing (sensor, index) also gives you the item's position, counted from zero. We will discuss the :key attribute in a moment - for now it is enough that it is a unique identifier:

<template>
  <div class="sensors-list" style="background: #0a0e27; padding: 1rem;">
    <!-- Iterating over an array -->
    <ul style="list-style: none; color: #00ff88;">
      <li v-for="sensor in sensors" :key="sensor.id"
          style="border-left: 2px solid #00b4d8; padding: 0.5rem; margin: 0.5rem 0;">
        {{ sensor.name }} - {{ sensor.value }}{{ sensor.unit }}
      </li>
    </ul>

    <!-- With index -->
    <div v-for="(sensor, index) in sensors" :key="sensor.id"
         style="color: #00b4d8;">
      [{{ index + 1 }}] {{ sensor.name }}: {{ sensor.value }}
    </div>
  </div>
</template>

The screen shows three li elements and three div elements numbered from 1, because we add one to the index for human readers. The sensor alias exists only inside the element with v-for. Instead of in you can also write of, which is closer to JavaScript's iterator syntax.

The data is an array of objects in a ref:

<script setup>
import { ref } from 'vue'

const sensors = ref([
  { id: 1, name: 'Oxygen Level', value: 21.5, unit: '%' },
  { id: 2, name: 'Temperature', value: 22, unit: '°C' },
  { id: 3, name: 'Pressure', value: 101.3, unit: 'kPa' }
])
</script>

Vue detects the methods that change an array, such as push(), splice() or sort(), so a new sensor added with push appears on the list right away. Methods like filter() or slice() return a new array and leave the old one alone - you have to assign the result to sensors.value.

Iterating Over Objects

v-for can also walk through an object's properties. The aliases are the value, the key and the index, in that order, and the order of properties follows the result of Object.values():

<template>
  <div class="module-specs" style="background: #0a0e27; padding: 1rem;">
    <!-- Values -->
    <div v-for="value in moduleDetails" :key="value" style="color: #00ff88;">
      {{ value }}
    </div>

    <!-- Key and value -->
    <div v-for="(value, key) in moduleDetails" :key="key"
         style="color: #00b4d8; border-bottom: 1px solid #00ff8833; padding: 0.25rem;">
      <strong>{{ key }}:</strong> {{ value }}
    </div>

    <!-- Key, value, and index -->
    <div v-for="(value, key, index) in moduleDetails" :key="key">
      {{ index }}. {{ key }}: {{ value }}
    </div>
  </div>
</template>

The last loop prints, for example, 0. name: Reactor Core Alpha. In the first one the value serves as the key only because all the values happen to be different here - the property name is the safer choice. The object itself is an ordinary reactive object:

<script setup>
import { reactive } from 'vue'

const moduleDetails = reactive({
  name: 'Reactor Core Alpha',
  type: 'Plasma Fusion',
  output: '500 MW',
  location: 'Central Hub, Mars Base'
})
</script>

Why is :key important?

Without a key, Vue updates a list with an in-place strategy: when the order of the data changes, it does not move the elements, it only patches the content of each one at its position. For plain text that is enough, but a form field or a component with state will then stay at the wrong position. A unique :key gives every element an identity. Compare three variants, each showing only the opening tag:

<template>
  <!-- GOOD - unique ID -->
  <div v-for="item in items" :key="item.id">

  <!-- BAD - index as key (problems with sorting/filtering) -->
  <div v-for="(item, index) in items" :key="index">

  <!-- BAD - no key -->
  <div v-for="item in items">
</template>

The index as a key behaves like no key at all, because after sorting the same number belongs to a different sensor. A missing key causes no error or console warning in Vue - it is caught only by a linter (the vue/require-v-for-key rule from eslint-plugin-vue). With duplicate keys, Vue warns in development mode while updating the list. A key should be a string or a number, ideally an identifier from the data.

v-for with v-if

When you want to show only the active sensors, it is tempting to add v-if to the element with v-for. In Vue 3, however, v-if has the higher priority, so it cannot see the sensor variable and rendering ends with an error. There are two correct ways out:

<template>
  <div class="active-sensors">
    <!-- GOOD - template wrapper -->
    <template v-for="sensor in sensors" :key="sensor.id">
      <div v-if="sensor.isActive" style="color: #00ff88;">
        {{ sensor.name }}
      </div>
    </template>

    <!-- OR - computed filter -->
    <div v-for="sensor in activeSensors" :key="sensor.id"
         style="color: #00ff88; border-left: 2px solid #00ff88; padding: 0.5rem;">
      {{ sensor.name }}
    </div>
  </div>
</template>

Both versions show the same names. With <template v-for> the key sits on the <template> tag, not on the child - otherwise the compiler reports an error. The second version uses a computed property:

<script setup>
import { ref, computed } from 'vue'

const sensors = ref([
  { id: 1, name: 'Oxygen Level', isActive: true },
  { id: 2, name: 'Dust Filter', isActive: false },
  { id: 3, name: 'Pressure', isActive: true }
])

const activeSensors = computed(() =>
  sensors.value.filter(s => s.isActive)
)
</script>

The original array does not change - the computed property returns a new, filtered one. The Vue docs recommend exactly this approach, and it is my choice too: the template stays simple and the filter has a name.

Number Range

v-for also accepts an integer and repeats the element that many times. Note that n starts at 1, not at 0:

<template>
  <div class="power-bars">
    <!-- Render 10 times -->
    <span v-for="n in 10" :key="n"
          style="display: inline-block; width: 20px; height: 20px; background: #00ff88; margin: 2px;">
    </span>

    <!-- Result: 10 green squares -->
  </div>
</template>

Ten squares make a power gauge, and with :class you could light up only those whose n does not exceed the energy level. In the next lesson you will reach an element of such a list directly through template refs.

Remember: v-for is the sensor assembly line, and :key is the serial number by which Vue recognizes every unit.

Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'

const crewMembers = ref([
  { id: 1, name: 'Dr. Elena Rodriguez', role: 'Commander', specialization: 'Astrobiology', status: 'active' },
  { id: 2, name: 'James Chen', role: 'Engineer', specialization: 'Mechanical Systems', status: 'active' },
  { id: 3, name: 'Sarah Johnson', role: 'Scientist', specialization: 'Geology', status: 'on-mission' },
  { id: 4, name: 'Marcus Williams', role: 'Pilot', specialization: 'Navigation', status: 'active' },
  { id: 5, name: 'Dr. Yuki Tanaka', role: 'Medical Officer', specialization: 'Space Medicine', status: 'active' }
])

const missionLogs = ref([
  { id: 101, sol: 42, type: 'discovery', message: 'Ice core samples found' },
  { id: 102, sol: 43, type: 'maintenance', message: 'Solar panel maintenance completed' },
  { id: 103, sol: 44, type: 'research', message: 'Rock mineral composition analysis' },
  { id: 104, sol: 45, type: 'communication', message: 'Contact with Mission Control Center' }
])

const equipment = ref([
  { id: 'eq1', name: 'Rover Explorer-1', status: 'operational', battery: 85 },
  { id: 'eq2', name: 'Drilling System', status: 'operational', battery: 92 },
  { id: 'eq3', name: 'Weather Station', status: 'maintenance', battery: 45 },
  { id: 'eq4', name: 'Communication Array', status: 'operational', battery: 100 }
])

const modules = ref([
  {
    id: 'm1',
    name: 'Habitat Module',
    sections: ['Living Quarters', 'Laboratory', 'Greenhouse']
  },
  {
    id: 'm2',
    name: 'Research Module',
    sections: ['Chemistry Lab', 'Biology Lab', 'Geology Lab']
  },
  {
    id: 'm3',
    name: 'Storage Module',
    sections: ['Food Storage', 'Equipment Storage', 'Water Tanks']
  }
])

function addCrewMember() {
  const newId = Math.max(...crewMembers.value.map(m => m.id)) + 1
  crewMembers.value.push({
    id: newId,
    name: 'New Recruit',
    role: 'Trainee',
    specialization: 'General',
    status: 'training'
  })
}

function removeCrewMember(id) {
  crewMembers.value = crewMembers.value.filter(member => member.id !== id)
}

function addLog() {
  const newId = Math.max(...missionLogs.value.map(l => l.id)) + 1
  const currentSol = Math.max(...missionLogs.value.map(l => l.sol)) + 1
  missionLogs.value.unshift({
    id: newId,
    sol: currentSol,
    type: 'info',
    message: 'New entry in the mission log'
  })
}
</script>

<template>
  <div class="mission-base">
    <h1>NOVA Base - Resource List</h1>

    <!-- v-for with array of objects + :key -->
    <section class="crew-section">
      <div class="section-header">
        <h2>Crew ({{ crewMembers.length }} members)</h2>
        <button @click="addCrewMember" class="btn btn-add">+ Add member</button>
      </div>

      <div class="crew-grid">
        <div
          v-for="member in crewMembers"
          :key="member.id"
          class="crew-card"
          :class="'status-' + member.status"
        >
          <div class="crew-header">
            <h3>{{ member.name }}</h3>
            <span class="role-badge">{{ member.role }}</span>
          </div>
          <p class="specialization">{{ member.specialization }}</p>
          <div class="crew-footer">
            <span class="status-badge" :class="member.status">
              {{ member.status }}
            </span>
            <button @click="removeCrewMember(member.id)" class="btn-remove">×</button>
          </div>
        </div>
      </div>
    </section>

    <!-- v-for with index -->
    <section class="logs-section">
      <div class="section-header">
        <h2>Mission Log</h2>
        <button @click="addLog" class="btn btn-add">+ New entry</button>
      </div>

      <div class="logs-list">
        <div
          v-for="(log, index) in missionLogs"
          :key="log.id"
          class="log-entry"
          :class="'log-' + log.type"
        >
          <span class="log-number">#{{ index + 1 }}</span>
          <span class="log-sol">Sol {{ log.sol }}</span>
          <span class="log-type">{{ log.type }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </section>

    <!-- v-for with nested loops -->
    <section class="modules-section">
      <h2>Base Modules</h2>
      <div class="modules-grid">
        <div
          v-for="module in modules"
          :key="module.id"
          class="module-card"
        >
          <h3>{{ module.name }}</h3>
          <ul class="sections-list">
            <li
              v-for="(section, sectionIndex) in module.sections"
              :key="module.id + '-' + sectionIndex"
              class="section-item"
            >
              <span class="section-number">{{ sectionIndex + 1 }}.</span>
              {{ section }}
            </li>
          </ul>
        </div>
      </div>
    </section>

    <!-- v-for over equipment with conditional styling -->
    <section class="equipment-section">
      <h2>Equipment</h2>
      <div class="equipment-list">
        <div
          v-for="item in equipment"
          :key="item.id"
          class="equipment-card"
        >
          <div class="equipment-name">{{ item.name }}</div>
          <div class="equipment-status" :class="item.status">
            {{ item.status }}
          </div>
          <div class="battery-container">
            <div class="battery-label">Battery:</div>
            <div class="battery-bar">
              <div
                class="battery-fill"
                :style="{ width: item.battery + '%' }"
                :class="{
                  'battery-low': item.battery < 50,
                  'battery-medium': item.battery >= 50 && item.battery < 80,
                  'battery-high': item.battery >= 80
                }"
              >
                {{ item.battery }}%
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <div class="info-box">
      <h3>v-for - Rendering Lists</h3>
      <ul>
        <li><strong>v-for="item in items"</strong> - iterate over an array</li>
        <li><strong>v-for="(item, index) in items"</strong> - with index</li>
        <li><strong>:key="item.id"</strong> - ALWAYS use a unique key</li>
        <li><strong>Nested loops</strong> - you can nest v-for</li>
        <li><strong>v-for with :class/:style</strong> - dynamic styling of list elements</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.mission-base {
  background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
  min-height: 100vh;
  padding: 2rem;
  color: #ffffff;
  font-family: 'Courier New', monospace;
}

h1 {
  text-align: center;
  color: #00ff88;
  text-shadow: 0 0 20px rgba(0, 255, 136, 0.5);
  margin-bottom: 3rem;
}

h2 {
  color: #00b4d8;
  margin-bottom: 1.5rem;
}

section {
  background: rgba(0, 255, 136, 0.05);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.btn-add {
  background: #00ff88;
  color: #0a0e27;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 5px;
  font-weight: bold;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  transition: all 0.3s ease;
}

.btn-add:hover {
  transform: scale(1.05);
  box-shadow: 0 5px 15px rgba(0, 255, 136, 0.4);
}

.crew-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.crew-card {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  border-radius: 8px;
  padding: 1.5rem;
  transition: all 0.3s ease;
}

.crew-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 180, 216, 0.3);
}

.crew-card.status-on-mission {
  border-color: #ffb400;
  background: rgba(255, 180, 0, 0.1);
}

.crew-header {
  display: flex;
  justify-content: space-between;
  align-items: start;
  margin-bottom: 0.5rem;
}

.crew-header h3 {
  color: #00ff88;
  margin: 0;
  font-size: 1.1rem;
}

.role-badge {
  background: #00b4d8;
  color: #ffffff;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
}

.specialization {
  color: #ffffff;
  margin: 0.5rem 0;
  font-size: 0.9rem;
}

.crew-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
  text-transform: uppercase;
}

.status-badge.active {
  background: rgba(0, 255, 136, 0.3);
  color: #00ff88;
}

.status-badge.on-mission {
  background: rgba(255, 180, 0, 0.3);
  color: #ffb400;
}

.status-badge.training {
  background: rgba(0, 180, 216, 0.3);
  color: #00b4d8;
}

.btn-remove {
  background: #ff0055;
  color: #ffffff;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  font-size: 1.5rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-remove:hover {
  transform: scale(1.1);
  box-shadow: 0 0 10px rgba(255, 0, 85, 0.5);
}

.logs-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.log-entry {
  display: grid;
  grid-template-columns: auto auto auto 1fr;
  gap: 1rem;
  padding: 1rem;
  background: rgba(0, 180, 216, 0.1);
  border-left: 4px solid #00b4d8;
  border-radius: 5px;
  align-items: center;
  transition: all 0.3s ease;
}

.log-entry:hover {
  background: rgba(0, 180, 216, 0.2);
  transform: translateX(5px);
}

.log-entry.log-discovery {
  border-left-color: #00ff88;
}

.log-entry.log-maintenance {
  border-left-color: #ffb400;
}

.log-number {
  color: #00b4d8;
  font-weight: bold;
  font-size: 0.9rem;
}

.log-sol {
  color: #00ff88;
  font-weight: bold;
}

.log-type {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  text-transform: uppercase;
}

.log-message {
  color: #ffffff;
}

.modules-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.module-card {
  background: rgba(0, 255, 136, 0.1);
  border: 2px solid #00ff88;
  border-radius: 8px;
  padding: 1.5rem;
}

.module-card h3 {
  color: #00ff88;
  margin-top: 0;
  margin-bottom: 1rem;
}

.sections-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.section-item {
  padding: 0.75rem;
  background: rgba(0, 180, 216, 0.1);
  border-radius: 5px;
  margin-bottom: 0.5rem;
  color: #ffffff;
  transition: all 0.3s ease;
}

.section-item:hover {
  background: rgba(0, 180, 216, 0.2);
  transform: translateX(5px);
}

.section-number {
  color: #00b4d8;
  font-weight: bold;
  margin-right: 0.5rem;
}

.equipment-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}

.equipment-card {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  border-radius: 8px;
  padding: 1.5rem;
}

.equipment-name {
  color: #00ff88;
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

.equipment-status {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
  display: inline-block;
  margin-bottom: 1rem;
  text-transform: uppercase;
}

.equipment-status.operational {
  background: rgba(0, 255, 136, 0.3);
  color: #00ff88;
}

.equipment-status.maintenance {
  background: rgba(255, 180, 0, 0.3);
  color: #ffb400;
}

.battery-container {
  margin-top: 1rem;
}

.battery-label {
  color: #ffffff;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
}

.battery-bar {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  height: 30px;
  overflow: hidden;
}

.battery-fill {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.battery-low {
  background: linear-gradient(90deg, #ff0055, #ff6600);
}

.battery-medium {
  background: linear-gradient(90deg, #ffb400, #ffd700);
  color: #0a0e27;
}

.battery-high {
  background: linear-gradient(90deg, #00ff88, #00b4d8);
  color: #0a0e27;
}

.info-box {
  background: rgba(0, 255, 136, 0.05);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 1.5rem;
  margin-top: 2rem;
}

.info-box h3 {
  color: #00ff88;
  margin-top: 0;
}

.info-box ul {
  list-style: none;
  padding: 0;
}

.info-box li {
  padding: 0.5rem 0;
  color: #ffffff;
  border-left: 3px solid #00b4d8;
  padding-left: 1rem;
  margin: 0.5rem 0;
}

.info-box strong {
  color: #00b4d8;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you iterate over an array in Vue?

  2. 2. Why is :key important in v-for?

  3. 3. How do you get the element index in v-for?

  4. 4. How do you read both the value and the key of each object property in v-for?

  5. 5. Which practice is recommended when you want to filter list elements?

Hands-on tasks in the game

  • Code editor

    Use v-for to render a list of sensors with :key and index.

  • Click in order

    Arrange the v-for syntax with :key (v-for first, then :key):

  • Vertical ordering

    Order the v-for arguments for objects from value to index:

  • Horizontal ordering

    Arrange the correct v-for syntax with :key:

  • Code editor

    Use v-for to iterate over object properties (value, key, index).

  • Vertical ordering

    Arrange from best to worst way of setting :key:

  • Click in order

    Arrange the correct usage of a template wrapper with v-for and v-if:

  1. Questionv-for Syntax
  2. QuestionThe :key Attribute in v-for
  3. Coding taskPractice: v-for List
  4. Click in orderv-for Syntax with key
  5. Questionv-for with Index
  6. Put in orderv-for Object Arguments
  7. Put in orderv-for Syntax with key
  8. Questionv-for over Object Properties
  9. Coding taskPractice: v-for over Object
  10. Put in orderCorrect :key Usage
  11. Questionv-for with v-if - Best Practice
  12. Click in orderv-for Syntax with Template Wrapper

Useful articles