3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

v-forによる繰り返しの描画

Posted at

v-forによる繰り返し

配列やオブジェクトをループ処理して、
要素を繰り返しを描画するには、v-forディレクティブを使用する。

index.html
// v-for 構文
<li v-for="各要素を代入する変数名 in 繰り返したい配列やオブジェクト">
index.html
<div id="app">
  <ul>
    <li v-for="item in items" v-bind:key="item.id">
  </ul>
</div>
app.js

new Vue ({
  el: '#app',
  data: {
    items: [
      { id: 1,
        title: '1番目のリスト',
      },
      { id: 2,
        title: '2番目のリスト',
      },
      { id: 3,
        title: '3番目のリスト',
      },
    ]
  }
})

dataオプションに登録されているitemsの配列から、v-forディレクティブを使って1つずつ要素を取り出し描画します。

Key の役割

v-bind:key="item.id"

v-forディレクティブでループしている要素に対しては、**v-bind:keyディレクティブにその要素として識別情報となる値(一意の値)**を指定することが推奨されています。Vueが各要素を効率よく追跡できるようにするため、ということのようです。

:keyv-bind:keyの省略構文。

不変でユニークなキーを設定しよう

要素の削除や並び替えも考慮して「不変でユニークなキー」を設定する必要があります。
ユニークな乱数を生成するuuidや、vue-uuidを使用して:keyの値を乱数で指定することができます。

uuid
vue-uuid

(例)「vue-uuid」を使用して:keyを指定する際は乱数を値に指定できるようにする場合

index.js

import Vue from 'vue';
import uuid from 'vue-uuid'; // 追加

Vue.use(uuid); // 追加

new Vue({
  el: '#app'
});

uuidモジュールをimportして、Vue.use()の引数に指定することによって
アプリケーションでuuidを使用できる様にします。

app.vue.js

data() {
  return {
    //省略
    items: [
      {
        id: this.$uuid.v4(), // バージョン4のUUIDは、乱数により生成される。
        title: '1番目のリスト',
      },
      {
        id: this.$uuid.v4(),
        title: '2番目のリスト'
      },
      {
        id: this.$uuid.v4(),
        title: '3番目のリスト'
      }
    ],
  }
}

これでidには乱数が指定されるようになりました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?