Vue v-for Components

Components can be reused with v-for to generate many elements of the same kind.

When generating elements with v-for from a component, it is also very helpful that props can be assigned dynamically based on values from an array.

Create Component Elements with v-for

We will now create component elements with v-for based on an array with food item names.

Example

App.vue:

<template>
  <h1>Food</h1>
  <p>Components created with v-for based on an array.</p>
  <div id="wrapper">
    <food-item
      v-for="x in foods"
      v-bind:food-name="x"/>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        foods: ['Apples','Pizza','Rice','Fish','Cake']
      };
    }
  }
</script>

FoodItem.vue:

<template>
  <div>
    <h2>{{ foodName }}</h2>
  </div>
</template>

<script>
  export default {
    props: ['foodName']
  }
</script>
Run Example »

v-bind Shorthand

To bind props dynamically we use v-bind, and because we will use v-bind much more now than before we will use the v-bind: shorthand : in the rest of this tutorial.


The 'key' Attribute

If we modify the array after the elements are created with v-for, errors can emerge because of the way Vue updates such elements created with v-for. Vue reuses elements to optimize performance, so if we remove an item, already existing elements are reused instead of recreating all elements, and element properties might not be correct anymore.

The reason for elements being reused incorrectly is that elements do not have a unique identifier, and that is exactly what we use the key attribute for: to let Vue tell the elements apart.

We will generate faulty behavior without the key attribute, but first let's build a web page with foods using v-for to display: food name, description, image for favorite food and button to change favorite status.

Example

App.vue:

<template>
  <h1>Food</h1>
  <p>Food items are generated with v-for from the 'foods' array.</p>
  <div id="wrapper">
    <food-item
      v-for="x in foods"
      :food-name="x.name"
      :food-desc="x.desc"
      :is-favorite="x.favorite"/>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        foods: [
          { name: 'Apples',
            desc: 'Apples are a type of fruit that grow on trees.',
            favorite: true },
          { name: 'Pizza',
            desc: 'Pizza has a bread base with tomato sauce, cheese, and toppings on top.',
            favorite: false },
          { name: 'Rice',
            desc: 'Rice is a type of grain that people like to eat.',
            favorite: false }
          { name: 'Fish',
            desc: 'Fish is an animal that lives in water.',
            favorite: true }
          { name: 'Cake',
            desc: 'Cake is something sweet that tastes good.',
            favorite: false }
        ]
      };
    }
  }
</script>

<style>
  #wrapper {
    display: flex;
    flex-wrap: wrap;
  }
  #wrapper > div {
    border: dashed black 1px;
    flex-basis: 120px;
    margin: 10px;
    padding: 10px;
    background-color: lightgreen;
  }
</style>

FoodItem.vue:

<template>
  <div>
    <h2>
      {{ foodName }}
      <img src="/img_quality.svg" v-show="foodIsFavorite">
    </h2>
    <p>{{ foodDesc }}</p>
    <button v-on:click="toggleFavorite">Favorite</button>
  </div>
</template>

<script>
  export default {
    props: ['foodName','foodDesc','isFavorite'],
    data() {
      return {
        foodIsFavorite: this.isFavorite
      }
    },
    methods: {
      toggleFavorite() {
        this.foodIsFavorite = !this.foodIsFavorite;
      }
    }
  }
</script>

<style>
  img {
    height: 1.5em;
    float: right;
  }
</style>
Run Example »

To see that we need the key attribute, let's create a button that removes the second element in the array. When this happens, without the key attribute, the favorite image is transferred from the 'Fish' element to the 'Cake' element, and that is NOT correct:

Example

The only difference from the previous example is that we add a button:

<button @click="removeItem">Remove Item</button>

and a method:

methods: {
  removeItem() {
    this.foods.splice(1,1);
  }
}

in App.vue.

Run Example »

As mentioned before: this fault, that the favorite image changes from 'fish' to 'cake' when an element is removed, has to do with Vue optimizing the page by reusing elements, and at the same time Vue cannot fully tell the elements apart. That is why we should always include the key attribute to uniquely mark each element when generating elements with v-for. When we use the key attribute, we no longer get this problem.

We do not use the array element index as the key attribute value because that changes when array elements are removed and added. We could create a new data property to keep a unique value for each item, like an ID number, but because the food items already have unique names we can just use that:

Example

We only need to add one line in App.vue to uniquely identify each element created with v-for and fix the problem:

<food-item
  v-for="x in foods"
  :key="x.name"
  :food-name="x.name"
  :food-desc="x.desc"
  :is-favorite="x.favorite"
/>
Run Example »

Vue Exercises

Test Yourself With Exercises

Exercise:

When generating elements with v-for, which specific attribute is always recommended to use?

<fish-type
  v-for="x in fish"
  :="x.id"
  :fish-name="x.name"
  :img-url="x.url"
/>

Start the Exercise



Copyright 1999-2023 by Refsnes Data. All Rights Reserved.