Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue Tutorial

Vue HOME Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue Why, How and Setup Vue First SFC Page Vue Components Vue Props Vue v-for Components Vue $emit() Vue Fallthrough Attributes Vue Scoped Styling Vue Local Components Vue Slots Vue v-slot Vue Scoped Slots Vue Dynamic Components Vue Teleport Vue HTTP Request Vue Template Refs Vue Lifecycle Hooks Vue Provide/Inject Vue Routing Vue Form Inputs Vue Animations Vue Animations with v-for Vue Build Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue Examples

Vue Examples Vue Exercises Vue Quiz Vue Syllabus Vue Study Plan Vue Server Vue Certificate

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



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.