Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

Vue Tutorial

Vue HOMEVue IntroVue DirectivesVue v-bindVue v-ifVue v-showVue v-forVue EventsVue v-onVue MethodsVue Event ModifiersVue FormsVue v-modelVue CSS BindingVue Computed PropertiesVue WatchersVue Templates

Scaling Up

Vue Why, How and SetupVue First SFC PageVue ComponentsVue PropsVue v-for ComponentsVue $emit()Vue Fallthrough AttributesVue Scoped StylingVue Local ComponentsVue SlotsVue v-slotVue Scoped SlotsVue Dynamic ComponentsVue TeleportVue HTTP RequestVue Template RefsVue Lifecycle HooksVue Provide/InjectVue RoutingVue Form InputsVue AnimationsVue Animations with v-forVue BuildVue Composition API

Vue Reference

Vue Built-in AttributesVue Built-in ComponentsVue Built-in ElementsVue Component InstanceVue DirectivesVue Instance OptionsVue Lifecycle Hooks

Vue Examples

Vue ExamplesVue ExercisesVue QuizVue SyllabusVue Study PlanVue ServerVue Certificate

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.

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 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 »

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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2025 Movatter.jp