TODO 프로젝트 – 10. 할 일 수정/삭제 하기

등록한 할 일들을 수정하고 삭제하는 기능을 추가합니다.
수정기능의 경우 리스트페이지에서 버튼으로 수정페이지로 이동을 하고 삭제는 리스트 페이지에서 작동됩니다.

1.리스트 페이지 수정 (frontend/src/commponents/page/list.vue)

template 영역

<template>
    <div class="list">
        <h2 class="comm__title">
            LIST
        </h2>
        <ul class="comm__list">
            <li v-for="(item,index) in todoItems" :key="index" :class="{ isEnd : item.todos_status == 1 }">
                <div class="comm__list-chk">
                    <input type="checkbox" class="chk" :checked="item.todos_status == 1" @change="todoCheck(item.todos_id,$event)">
                </div>
                <div class="comm__list-tit">{{item.todos_title}}</div>
                <div class="comm__list-con">
                    {{item.todos_desc}}
                </div>
                <div class="comm__list-btn">
                    <button type="button" class="btn btn--modify" v-on:click="todoModifyPage(item.todos_id);">MODIFY</button>
                    <button type="button" class="btn btn--cancel" v-on:click="todoDelete(item.todos_id);">DELETE</button>
                </div>
            </li>
        </ul>
        <div class="comm__list-bottom">
            <a href="/add" class="btn btn--large btn--confirm">
                ADD
            </a>
        </div>
    </div>
</template>

이전 리스트에서 버튼 두개가 추가되었습니다.
수정 버튼과 삭제 버튼입니다.
수정과 삭제 모두 할 일의 ID값을 파라미터로 전달합니다.

script 영역

<script>
export default  {
    data() {
        return {
            todoItems : []
        }
    },
    methods : {
        todoModifyPage : function(id) {
            this.$router.push({
                name : 'todos_modify',
                params : {
                    id : id
                }
            });
        },
        todoDelete : function(id) {
            this.$http.post('/api/todo/delete',{id : id}).then((response) => {
                this.getListAll();
            });
        },
        todoCheck : function (id,event) {
            this.$http.post('/api/todo/check',{id : id, isChk : event.target.checked}).then((response) => {
                this.getListAll();
            });
        },
        getListAll : function () {
            this.$http.get('/api/todo').then((response) => {
                if (response.data.message) {
                    alert(response.data.message);
                    this.$router.push('/login');
                } else {
                    this.todoItems = response.data.data.map(function (data) {
                        return data;
                    });
                }
            });
        }
    },
    created () {
        this.getListAll();
    }
}
</script>

수정 버튼을 클릭하면 todoModifyPage 함수가 실행되는데 이 함수는 modify 라우터를 호출하고
파라미터로 클릭한 할 일의 ID값을 넘깁니다.
삭제 버튼을 클릭하면 todoDelete 함수가 실행되고, 삭제 API를 호출합니다.

2.삭제 API 추가 (backend/app.js)

app.post('/api/todo/delete', function (req,res,next) {
    var params = [req.body.id];
    connection.query(
        "DELETE from todos WHERE `todos_id` = ?", params,
        function (error, results, fields) {
            if (error) console.log(error);
            res.send(true);
        }
    );
});

이전 API 호출과 마찬가지로 할 일을 성공적으로 삭제하면 true를 리턴합니다.

3.수정 페이지 추가 (frontend/src/commponents/page/modify.vue)

<template>
    <div class="add">
        <h2 class="comm__title">MODIFY</h2>
        <div class="ipt__box">
            <input type="text" ref="tit" class="ipt"  v-model="newTodoTitle">
        </div>
        <div class="ipt__box">
            <input type="text" class="ipt"  v-model="newTodoDesc" v-on:keyup.enter="todoModify">
        </div>
        <div class="ipt__btn">
            <a href="#" class="btn btn--confirm btn--large" v-on:click="todoModify">MODIFY</a>
        </div>
    </div>
</template>

<script>
export default {
    name : 'todos_modify',
    data() {
        return {
            id : this.$route.params.id,
            newTodoTitle :'',
            newTodoDesc :''
        }
    },
    methods : {
        todoModify() {
            this.$http.post('/api/todo/modify',{id : this.id, title : this.newTodoTitle, desc : this.newTodoDesc}).then((response) => {
                if (response.data.success == true) {
                    alert('수정되었습니다.');
                    this.$router.push('/list');
                }
            });
        }
    },
    created () {
        var id = this.id;
        this.$http.get(`/api/todo/modify/${id}`).then((response) => {
            this.newTodoTitle = response.data.data[0].todos_title;
            this.newTodoDesc = response.data.data[0].todos_desc;
        });
    }
}
</script>

수정 화면에서는 첫 인스턴스 생성시 라우터를 통해 넘어온 ID 값으로 DB에서 할 일을 불러옵니다.
불러온 데이터를 폼에 넣고 v-model로 동기화를 시켜줍니다.
수정 버튼을 누르면 수정 API를 호출합니다.

4.수정 API 추가 (backend/app.js)

app.post('/api/todo/modify', function (req,res,next) {
    var params = [req.body.title,req.body.desc,req.body.id];
    connection.query(
        "UPDATE todos SET `todos_title` = ?, `todos_desc` = ? WHERE `todos_id` = ?", params,
        function (error, results, fields) {
            if (error) console.log(error);
            res.json({
                success : true
            });
        }
    );
});

수정이 성공적으로 완료되면 true를 리턴합니다.