seller/Menu1.vue 물품관리

팡태(❁´◡`❁)·2022년 2월 14일
0

3rd_20220124

목록 보기
20/29
<template>
  <div>
        <el-card class="fade-in-left">
        <h3 class="fade-in-left">물품관리</h3>
            <el-button @click="handlePage">일괄추가</el-button>
            <el-button @click="handleDeleteBatchAction">일괄삭제</el-button>
            <el-button @click="handleUpdateBatchAction">일괄수정</el-button>


            <table style="margin:20px;">
                <tr>
                    <th></th>
                    <th>물품코드</th>
                    <th>이미지</th>
                    <th>물품명</th>
                    <th>가격</th>
                    <th>수량</th>
                    <th>내용</th>
                    <th>등록일자</th>                
                </tr>

                <tr v-for="(item, idx) in state.items" :key="item">
                    <td>
                        <input type="checkbox" :value="item._id" v-model="state.chk" />
                    </td>

                    <td>
                        <el-button @click="handleDetailPage(item._id)">{{item._id}}</el-button>
                    </td>

                    <td>
                        <img :src="item.imageUrl" style="width:50px; height:50px">
                        <input type="file" @change="handleImage($event, idx)" />
                    </td>
                    <td><el-input type="text" v-model="item.name" /></td>
                    <td><el-input type="text" v-model="item.price" /></td>
                    <td><el-input type="text" v-model="item.quantity" /></td>
                    <td><el-input type="text" v-model="item.content" /></td>
                    <td>{{ item.regdate }}</td>
                    <td>
                        <el-button type="danger" @click="handleDeleteAction([item._id])">삭제</el-button>
                        <el-button type="success" @click="handleUpdateAction(idx)">수정</el-button>
                    </td>
                </tr>
            </table>

      </el-card>
  </div>
</template>

<script>
import { reactive, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

export default {
    setup () {

        const router = useRouter();

        const state = reactive({
            chk  : [],
            token: sessionStorage.getItem("TOKEN")
        });

        // 백엔드에서 목록을 받아오는 부분. 갱신하는 메소드
        const handleLoadData = async() => {
            const url      = `/seller/selectlist`;
            const headers  = { 
                "Content-Type": "application/json",
                "token": state.token 
            };
            const response = await axios.get(url, { headers });
            console.log(response.data);

            if(response.data.status === 200) {
                state.items = response.data.result;
            }        
        }

        onMounted( async() => {
            await handleLoadData();
        });

        const handlePage = async() => {
            router.push({ name: "Menu1Insert" });
        }

        const handleDeleteAction = async(code) => {
            if(confirm('삭제하시겠습니까?')){
                const url = `/seller/delete`;
                const headers = { 
                    "Content-Type": "application/json",
                    "token"       : state.token
                };

                // { "code": [1036] }
                const body = { code: code };
                console.log(body);
                const response = await axios.delete(url, { headers: headers, data: body });
                console.log(response.data);
                if(response.data.status === 200) {
                    // 삭제했다면, 백엔드에서 데이터 갱신해야 함
                    await handleLoadData();
                }
            }
        }

        const handleImage = async(e, idx) => {
            if(e.target.files[0]){
                // 첨부했다면 state에 이미지 정보를 넣어라
                state.items[idx].image = e.target.files[0];
            }
            else {
                state.items[idx].image = '';
            }
        }

        const handleUpdateAction = async(idx) => {
            const url     = `/seller/update`;
            const headers = { 
                "Content-Type": "multipart/form-data",
                "token"       : state.token                
            };

            const body = new FormData();
            body.append('image',    state.items[idx].image);
            body.append('code',     state.items[idx]._id);
            body.append('title',    state.items[idx].name);
            body.append('price',    state.items[idx].price);
            body.append('content',  state.items[idx].content);
            body.append('quantity', state.items[idx].quantity);
            

            const response = await axios.put(url, body, { headers: headers });
            console.log(response.data);

            if(response.data.status === 200) {
                alert('수정 완료');
                await handleLoadData();
            }
        }

        const handleDeleteBatchAction = async() => {    
            await handleDeleteAction(state.chk);
        }

        const handleUpdateBatchAction = async() => {
            let arr = [];
            for(let i=0; i<state.items.length; i++) {   // 전체 개수
                for(let j=0; j<state.chk.length; j++) { // 체크한 개수
                    if(state.items[i]._id === state.chk[j]) {
                        arr.push(state.items[i]);       // 전체 중에 체크한 것만 arr에 들어감
                    }
                }
            }

            console.log(arr);

            const url     = `/seller/update`;
            const headers = { 
                "Content-Type": "multipart/form-data",
                "token"       : state.token                
            };

            const body = new FormData();
            
            for(let i=0; i<arr.length; i++) {
                body.append('image',    arr[i].image);
                body.append('code',     arr[i]._id);
                body.append('title',    arr[i].name);
                body.append('price',    arr[i].price);
                body.append('content',  arr[i].content);
                body.append('quantity', arr[i].quantity);
            }

            const response = await axios.put(url, body, { headers: headers });
            console.log(response.data);

            if(response.data.status === 200) {
                alert('수정 완료');
                await handleLoadData();
                state.chk = [];
            }
        }

        const handleDetailPage = async(code) => {
            router.push({ name: 'Menu1Detail', query: { code: code } });
        }

        return { 
            state, 
            handleLoadData, 
            handlePage, 
            handleDeleteAction, 
            handleImage, 
            handleUpdateAction,
            handleDeleteBatchAction,
            handleUpdateBatchAction,
            handleDetailPage,
        }
    }
}

</script>

<style lang="scss" scoped>
  table {
    width: 100%;
    border: 1px solid #9e9e9e;
    border-collapse: collapse;
  }
  th, td {
    border: 1px solid #a3a3a3;
    padding: 10px;
  }
    @import url(../../assets/mystyle.css);

</style>

0개의 댓글