TIL55. Vue Todo-list

조연정·2020년 12월 6일
0

지금까지 배운 내용을 토대로 간단한 '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를 부여하기 위해서

❓❗️

  • input에 한글을 입력하고 엔터키를 치면, 한글 값이 담긴 이벤트가 발생하고, 바로 빈 값이 담긴 이벤트가 한번 더 발생하는 문제점이 발생했다.
    -> keyup,keydown시 한글을 입력하고 엔터를 치면 두번 호출하는 것이었다.keypress를 입력하여 문제를 해결할 수 있었다.
profile
Lv.1🌷

0개의 댓글