추가/삭제 기능 구현

hyuckhoon.ko·2022년 5월 3일
0

1. 코드

    <div id="app">
        <h1>My To do App !</h1>
        <strong>서로 해야할 일을 입력해 보아요</strong>
        <br>
        <div class="inputBox">
            <input type="text" class="name" placeholder="작성자" v-model="name">
            <input type="text" class="item" placeholder="해야할 일을 입력해주세요" v-model="newTodoItem" v-on:keyup.enter="addTodo()">
            <button v-on:click="addTodo()">추가</button>
        </div>

        <ul class="todoList">
            <li v-for="(todo, index) in todoList">
                <span>{{ todo.name }} :: {{ todo.item }}</span>
                <span class="removeBtn" @click="removeTodo(index)">&#x00D7</span>
            </li>
        </ul>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data: function() {
                return {
                    name: '',
                    newTodoItem: '',
                    todoList: [
                        {name: '나', item: '지금 듣고 있는 강의 완강하기'},
                        {name: '나', item: '퍼블리싱하기'},
                        {name: '나', item: '최종 제출되게 일단 만들어 놓기'},
                        {name: '나', item: '코드 리뷰 받기'},
                    ]
                }
            },
            methods:{
                addTodo: function () {
                    if (this.newTodoItem === "") return;
                    if (this.name === "") this.name = "나";
                    this.todoList.push({name: this.name, item: this.newTodoItem});
                    this.name = "";
                    this.newTodoItem = "";
                },
                removeTodo: function (index) {
                    console.log('delete');
                    this.todoList.splice(index, 1)
                }
            }
        })
    </script>
    
</body>
</html>

2. 추가 기능

addTodo: function () {
	if (this.newTodoItem === "") return;
	if (this.name === "") this.name = "나";
	this.todoList.push({name: this.name, item: this.newTodoItem});
	this.name = "";
	this.newTodoItem = "";
}              

3. 삭제 기능

removeTodo: function (index) {
	this.todoList.splice(index, 1)
}

0개의 댓글