とーますメモ

Ruby on Rails / Goなどの学習メモ

【Vue.js】v-forの配列を削除すると、最後の行が消される問題

v-forで配列内をループで回して、表示させており
その中で以下のように、削除を行う機能を実装したのだが
削除すると選択した行が消されず、最後の行が消されるという変な現象が発生した。

[HTML]

<tbody>
  <tr
    is="sample-component"
    v-for="(item, index) in items"
    v-bind:index="index"
    v-bind:item="item"
    :key="index"
    v-on:remove="remove_item"
  ></tr>
</tbody>

[JS]

this.items.splice(index, 1);

原因を調べてみると、「:key」属性に「index」を設定していたのが原因だった。

In scenarios like this the most common problem is the v-for item keys. Your are keying each item by the index, but the index of each item is not constant because items can be removed from the list. Try using unique keys that are associated with item in the list.

by V-for and deleting components - Get Help - Vue Forum

なので設定する:keyをコンポーネントに属する唯一の値にすることで問題が解消された。
v-forのkeyにはindexを設定してはいけません!

[解決済みコード]

<tbody>
  <tr
    is="sample-component"
    v-for="(item, index) in items"
    v-bind:index="index"
    v-bind:item="item"
    :key="item.id"
    v-on:remove="remove_item"
  ></tr>
</tbody>