지금까지 배운 내용을 토대로 간단한 'todo-list'를 만들어보자.
//list.vue
<template>
<div class="mb-2 d-flex">
<div>
<input type="checkbox" :checked="list.checked" @change="toggleCheckbox" />
</div>
<span
class="ml-3 flex-grow-1"
:class="list.checked ? 'text-muted' : ''"
:style="list.checked ? 'text-decoration:line-through' : ''"
>{{ list.text }}
</span>
<button class="btn btn-danger btn-sm flex-shrink-1" @click="deleteList">
DELETE
</button>
</div>
</template>
<script>
export default {
props: {
list: {
type: Object,
required: true,
},
},
methods: {
toggleCheckbox(e) {
this.$emit("toggle-checkbox", {
id: this.list.id,
checked: e.target.checked,
});
},
deleteList() {
this.$emit('click-delete', this.list.id)
}
},
};
</script>
//Todo.vue
<template>
<div class="container">
<h1 class="text-center">Todo-list</h1>
<input
v-model="todoText"
type="text"
class="w-100 p-2"
placeholder="Type todo"
@keypress.enter="addTodo"
/>
<hr />
<Lists
v-for="list in todos"
:key="list.id"
:list="list"
@toggle-checkbox="toggleCheckbox"
@click-delete="deleteList"
/>
</div>
</template>
<script>
import Lists from "./Lists";
export default {
components: {
Lists,
},
data() {
return {
todoText: "",
todos: [
{ id: 1, text: "몽이 밥 주기", checked: false },
{ id: 2, text: "몽이 산책하기", checked: false },
{ id: 3, text: "몽이 사료사기", checked: false },
{ id: 4, text: "몽이 산책하기", checked: false },
],
};
}
methods: {
deleteList(id) {
this.todos = this.todos.filter((list) => list.id !== id);
},
addTodo(e) {
if (e.key === "Enter") {
this.todos.push({
id: this.todos[this.todos.length - 1].id + 1,
text: e.target.value,
checked: false,
});
this.todoText = "";
}
},
toggleCheckbox({ id, checked }) {
const index = this.todos.findIndex((list) => {
return list.id === id;
});
this.todos[index].checked = checked;
},
},
};
</script>
새로 추가된 값에 id를 부여하기 위해서