[Django, Vue]Django + Vue CRUD 구현 1 - Front end
SW개발/Django

[Django, Vue]Django + Vue CRUD 구현 1 - Front end

 

이전 까지의 작업을 통해 이제 우리는 DRF Server 에서 데이터를 GET 할 수 있게 되었다.

이번 포스팅에서는 GET을 포함한 CRUD 기능을 구현해볼 것이다.

 

데이터를 가져왔으니 화면에 가져온 데이터를 출력해야 할 것이다. 데이터를 가져오는 방법에는 다양한 방법들이 존재하는데 여기서는

mounted를 사용하여 페이지 로드 시 데이터를 가져오는 방법을 택할 것이다.

 

App.vue 

// App.vue

<script>
import axios from "axios";
import Header from "./components/Header.vue";
import Content from "./components/Content.vue";
import Footer from "./components/Footer.vue";

let url = "http://localhost:8000/user/";  // 장고 drf 서버 주소

export default {
  data: () => {
    return {
      userList: []
    };
  },
  components: {
    "header": Header,
    "content": Content,
    "footer": Footer
  },
  mounted() { // DOM 객체가 생성된 후 DRF server 에서 데이터를(userList) 가져와 저장
    axios({
      method: "GET",
      url: url 
    })
      .then(response => {
        this.userList = response.data;
      })
      .catch(response => {
        console.log("Failed", response);
      });
  },
  methods: {  // CRUD 로직 
    getUserList: function() {},
    updateUserList: function() {},
    deleteUserList: function() {}
  }
};
</script>

mounted 를 활용하여 DOM 객체가 생성된 후에 DRF server로부터 userList를 가져와서 저장해주는 코드를 App.vue 에 작성하였다.

methods 부분에서는 아직 구현하지는 않았지만 추후에 CRUD 로직을 구현하기 위한 메소드들을 미리 선언해 두었다.

userList : [] 부분을 통하여 데이터를 저장했으니 이 데이터를 props 를 통해 화면에 출력해볼 것이다.

 

컴포넌트간 데이터 통신

Vue.js 에서는 상위 컴포넌트(App.vue)와 하위 컴포넌트(Header, Content, Footer)간에 통신을 하기 위해서는 2가지의 방법이 있다.

  • 상위 컴포넌트 -> 하위 컴포넌트로 데이터 전달 : props 속성 이용
  • 하위 컴포넌트 -> 상위 컴포넌트로 데이터 전달 : event emit 이용

우리는 상위 컴포넌트에 userList 라는 데이터를 하위 컴포넌트로 전달할 것이기 때문에 props 속성을 이용할 것이다.

 

App.vue

// App.vue

<template>
  <div>
    <header></header>
    <!-- v-bind:하위컴포넌트 속성명="상위 컴포넌트 전달할 데이터명"  -->
    <content v-bind:propsdata="userList"></content> 
    <footer></footer>
  </div>
</template>

export default {
	// ...
    components: {
        "header": Header,
        "content": Content,
        "footer": Footer,
    },
    // ...
};

상위 컴포넌트인 App.vue 에서 proposdata를 속성명, userList를 데이터로 하여 바인딩 해준다. 그 후 아래 부분의 components 에 해당 컴포넌트들을 등록하여 준다. 

 

Content.vue

// components/Content.vue 파일 수정

<template>
    <div>
        <v-container fluid>
            <v-layout column>
                <v-flex xs12>
                    <h3 class="subject">User CRUD</h3>
                </v-flex>
                <v-flex column>
                    <v-row>
                        <v-col cols="4" md="4">
                            <!-- 합이 12가 되면 전체 화면을 사용한다는 의미입니다. -->
                            <v-text-field v-model="username" :counter="15" label="Username" required></v-text-field>
                        </v-col>
                        <v-col cols="4" md="4">
                            <v-text-field v-model="age" label="Age" required></v-text-field>
                        </v-col>
                        <v-col cols="4" md="4">
                            <v-text-field v-model="city" :counter="15" label="City" required></v-text-field>
                        </v-col>
                    </v-row>

                    <v-form ref="form" v-model="valid" lazy-validation>
                        <v-btn @click="create" style="background: green">create</v-btn>
                        <v-btn @click="clear" style="background: red">clear</v-btn>
                    </v-form>
                </v-flex>

                <!-- 수정 부분 start -->
                <v-flex class="userList" column>
                    <v-card max-width="600" tile>
                        <v-list-item v-for="(data, index) in propsdata" v-bind:key="index">
                            <v-list-item-content>
                                <v-list-item-title>이름 : {{ data.username }}</v-list-item-title>
                                <v-list-item-subtitle>나이 : {{ data.age }}세, 거주지: {{ data.city }}</v-list-item-subtitle>
                            </v-list-item-content>
                        </v-list-item>
                    </v-card>
                </v-flex>
                <!-- 수정 부분 end -->
            </v-layout>
        </v-container>
    </div>
</template>

<!-- 수정 부분 start -->
<script>
export default {
	props:["propsdata"]
};
</script>
<!-- 수정 부분 end -->

<style>
.subject {
    color: blue;
    font-style: oblique;
    padding: 30px;
    text-align: center;
}
.userList {
    margin: 30px 0px 30px 0px;
}
</style>

 

Content.vue 컴포넌트로 이동하여 상위 컴포넌트인 App.vue 에서 전달받은 propsdata를 v-for 구문을 통해 장고 DB에 저장된
userlist를 전부 GET 하는 기능을 구현하였다.

 

지금 상태에서는 저장된 데이터가 없으므로 장고 서버에 접속하여 임의의 데이터를 생성해주자. 

 

데이터를 생성해 주었으니 vue 서버에 접속하여 장고 서버의 DB에 저장된 유저 데이터가 모두 GET 되어 출력되는 것을 확인할 수 있다.

 

다음 포스팅에서는 Create 기능을 구현해 볼 것이다.

 

728x90