こちらのサイトを参考に、モーダルを使ってリストからidを指定して1件削除しようとしたら、なぜかリストの最後だけ削除されてしまう。
(実際はvuexを使ってたり、追加・変更ボタンもあるが簡略化)
coping.vue
<template>
<div>
<table>
<thead>
<tr>
<th width="30%">名前</th>
<th width="50%">説明</th>
<th></th>
</tr>
<tr v-for="(coping, index) in coping_list" :key="index" class="coping">
<td>
<input v-model="coping.name" type="text" />
</td>
<td>
<input v-model="coping.detail" type="text" />
</td>
<!-- 押されたら削除モーダルを開く -->
<td @click="openDeleteModal()">
<i class="fas fa-times"></i>
</td>
<!-- 削除しますか?のモーダルを開く
「削除」で1件削除(closeDeleteModal()を呼び出す)
「キャンセル」でモーダルを閉じる(deleteCoping()を呼び出す)
-->
<DeleteModal
v-if="is_delete_modal"
@close="closeDeleteModal()"
@delete="deleteCoping(coping.id)"
/>
</tr>
</thead>
</table>
</div>
</template>
<script>
import DeleteModal from '~/components/DeleteModal.vue'
export default {
components: {
DeleteModal
},
data() {
return {
coping_list: [
{ id: 1, name: 'aaa', detail: 'AAA' },
{ id: 2, name: 'bbb', detail: 'BBB' }
],
// モーダルの表示・非表示を管理
is_delete_modal: false
}
},
methods: {
// IDで指定したコーピングの削除
// モーダルからcoping.idを指定すると、なぜか最後のIDが指定されてしまう
deleteCoping(copingId) {
// 引数に持ったID以外のリストを作る
this.coping_list = this.coping_list.filter(
(coping) => coping.id !== copingId
)
this.closeDeleteModal()
},
// モーダルを表示する
openDeleteModal() {
this.is_delete_modal = true
},
// モーダルを非表示にする
closeDeleteModal() {
this.is_delete_modal = false
}
}
}
</script>
原因
削除モーダルをテーブルの行ごとに作っていたのが誤作動の原因。モーダルを呼び出したときに最後のモーダルだけが実行されていた。
解決策
削除モーダルを1つだけにする。
削除するIDは削除用IDとしてdata()に持つ
coping.vue
<template>
<div>
<table>
<thead>
<tr>
<th width="30%">名前</th>
<th width="50%">説明</th>
<th></th>
</tr>
<tr v-for="(coping, index) in coping_list" :key="index" class="coping">
<td>
<input v-model="coping.name" type="text" />
</td>
<td>
<input v-model="coping.detail" type="text" />
</td>
<!-- 押されたら削除モーダルを開く
この時に押された行のIDを渡す -->
<td @click="openDeleteModal(coping.id)">
<i class="fas fa-times"></i>
</td>
</tr>
</thead>
</table>
<!-- 削除モーダルはテーブルの外に出す
deleteCoping()の引数はdata()から貰う-->
<DeleteModal
v-if="is_delete_modal"
@close="closeDeleteModal()"
@delete="deleteCoping(delete_id)"
/>
</div>
</template>
<script>
import DeleteModal from '~/components/DeleteModal.vue'
export default {
components: {
DeleteModal
},
data() {
return {
coping_list: [
{ id: 1, name: 'aaa', detail: 'AAA' },
{ id: 2, name: 'bbb', detail: 'BBB' }
],
// モーダルの表示・非表示を管理
is_delete_modal: false,
// 削除用のID
delete_id: null
}
},
methods: {
// IDで指定したコーピングの削除
// モーダルからcoping.idを指定すると、なぜか最後のIDが指定されてしまう
deleteCoping(copingId) {
// 引数に持ったID以外のリストを作る
this.coping_list = this.coping_list.filter(
(coping) => coping.id !== copingId
)
this.closeDeleteModal()
},
openDeleteModal(copingId) {
this.is_delete_modal = true
// ここで削除用IDを設定
this.delete_id = copingId
},
closeDeleteModal() {
this.is_delete_modal = false
}
}
}
</script>
ちゃんと指定したIDのリストを削除してくれるようになった。めでたしめでたし。


