Vue v-for Components
Components can be reused withv-for to generate many elements of the same kind.
When generating elements withv-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 withv-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 usev-bind, and because we will usev-bind much more now than before we will use thev-bind: shorthand: in the rest of this tutorial.
The 'key' Attribute
If we modify the array after the elements are created withv-for, errors can emerge because of the way Vue updates such elements created withv-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 thekey attribute for: to let Vue tell the elements apart.
We will generate faulty behavior without thekey attribute, but first let's build a web page with foods usingv-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 thekey attribute, let's create a button that removes the second element in the array. When this happens, without thekey 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); }}inApp.vue.
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 thekey attribute to uniquely mark each element when generating elements withv-for. When we use thekey attribute, we no longer get this problem.
We do not use the array element index as thekey 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 inApp.vue to uniquely identify each element created withv-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 »
