ToDoリストにおけるIDの連番、エラーについて
現在、Vueを使いTodoリストを作成しています。
リストを追加するとIDが振り当てられるように作成したいのですが、一度削除をして、追加を押すと連番にならず、削除したリストの次の数字から振り当てられてしまいます。
例:3つリストを追加し、全て削除してから新しく追加を押すと、0からではなく、ID4から追加されていってしまいます。
また、リストにIDを持たせたいのですが、削除すると連番に振りなおされてしまいます。
例:ID1,2,3 があり ID:2を削除したら 1,3が残るようにしたい
どのように書き換えればよいのでしょうか。
よろしくお願いいたします。
発生している問題・エラーメッセージ
また、computedプロパティにエラーメッセージが出ているのですが、検索しても似たような記事が出てこなく詰まってしまったので、解決策いただけると嬉しいです、
(HTML内にVUEを読み込んで、書くスタイルだとこエラーは出なかったのですが、インストールして進めていく環境に持ってきたら、エラーメッセージが出てきてしまいました。)
error Expected to return a value in "filteredTodos" computed property
該当のソースコード
vue
1 2<template> 3 <div id="app"> 4 <body> 5 <h1>ToDoリスト</h1> 6 <label 7 ><input 8 type="radio" 9 name="list" 10 value="all" 11 v-model="filter" 12 />すべて</label 13 > 14 <label 15 ><input 16 type="radio" 17 name="list" 18 value="active" 19 v-model="filter" 20 />作業中</label 21 > 22 <label 23 ><input 24 type="radio" 25 name="list" 26 value="completed" 27 v-model="filter" 28 />完了</label 29 > 30 31 <table> 32 <tr v-for="(todo, key) in filteredTodos" :key="key"> 33 <td>{{ todo.id }}</td> 34 <td>{{ todo.title }}</td> 35 <td> 36 <button @click="statusChange(todo.id)"> 37 <span>{{ todo.statusBtn }}</span> 38 </button> 39 </td> 40 <td> 41 <button @click="deleteTask(todo.id)">{{ todo.delBtn }}</button> 42 </td> 43 </tr> 44 </table> 45 46 <h2>新規タスクの追加</h2> 47 <form @submit.prevent="addTask"> 48 <input type="text" v-model="newTask" /> 49 <input type="submit" value="追加" class="button" /> 50 </form> 51 </body> 52 </div> 53</template> 54 55<script> 56export default { 57 data() { 58 return { 59 id: 0, 60 statusBtn: "", 61 newTask: "", 62 todos: [], 63 filter: "all", 64 }; 65 }, 66 computed: { 67 filteredTodos() { 68 if (this.filter === "all") { 69 return this.todos; 70 } else if (this.filter === "completed") { 71 return this.todos.filter((todo) => { 72 return todo.statusBtn === "完了"; 73 }); 74 } else if (this.filter === "active") { 75 return this.todos.filter((todo) => { 76 return todo.statusBtn === "作業中"; 77 }); 78 } 79 }, 80 methods: { 81 addTask: function () { 82 let item = { 83 id: this.id++, 84 title: this.newTask, 85 statusBtn: "作業中", 86 delBtn: "削除", 87 }; 88 this.todos.push(item); 89 this.newTask = ""; 90 }, 91 statusChange: function (id) { 92 for (let todo of this.todos) { 93 if (todo.id === id) { 94 if (todo.statusBtn === "作業中") { 95 todo.statusBtn = "完了"; 96 } else { 97 todo.statusBtn = "作業中"; 98 } 99 break; 100 } 101 } 102 }, 103 deleteTask: function (smt) { 104 let index = this.todos.indexOf(smt); 105 this.todos.splice(index, 1); 106 }, 107 }, 108 }, 109}; 110</script>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/07/15 06:49
2021/07/15 07:13
2021/07/16 01:24
2021/07/16 02:01
2021/07/17 04:22