Frontend-Vuejs
Postman 없이 api 호출해 db table 만들기 (3) table에 db값 넣기
jiwoolee
2021. 7. 28. 16:26
지난 게시글에서,
backend와 frontend를 연동시켰다.
front단에서 script 함수 만들어서 axios로 api를 호출해보자
backend 프로젝트에서 node src로 연결 확인 후 postman에서 바디 확인해보면 아래와 같다
이런 데이터를 front단에서 보는 게 목표다
front단에서 script 함수를 만들어주자
<template>
<div>
<table>
<thead>
<tr>
<th colspan="2">DB info 보기</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserID</td>
<td>Country</td>
</tr>
<tr>
<td>1 아이디</td>
<td>1 country</td>
</tr>
<tr>
<td>2 id</td>
<td>2 country</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "myTable",
// data() { // return {}; // },
mounted() { this.getData(); },
methods: { async getData() {
try { const res = await axios.get(
"http://localhost:4003/api/v1/infos/get" );
console.log(res);
}
catch (error) {
console.err(error);
}
},
},
};
</script>
<style>
table,
td {
border: 1px solid #333;
}
thead,
tfoot {
background-color: #333;
color: #fff;
}
</style>
npm run serve로 서버에서 확인을 해보면
오브젝트 형태로 불러와진 res를 볼 수 있다.
나는 data만 원하니까 수정을 해줘야지
methods: {
async getData() {
try {
const {data} = await axios.get( "http://localhost:4003/api/v1/infos/get" );
console.log(data);
}
catch (error) {
console.err(error);
}
},
},
이렇게 하면 오브젝트에서 data만 빼서 확인을 할 수 있다
근데 나는 (data) 인덱스 0의 내부 정보, 인덱스 1의 내부 정보를 테이블에 각각 써주고 싶잖아
methods: {
async getData() {
try {
const { data } = await axios.get( "http://localhost:4003/api/v1/infos/get" );
//console.log(data)
const UserID0 = data[0].UserID;
const UserID1 = data[1].Country;
const Country0 = data[0].UserID;
const Country1 = data[1].Country;
}
}
}
이러면 값만 뽑아낼 수 있지
이제 아래 그림처럼 template-mustache 사용해서 테이블에 db 값만 넣어주면 되겠다
이제 UserID_first, .... 가 무엇인지 알려줄 수 있는 인스턴스 등록만 남았다.
우선 data()에 공백으로 먼저 넣어주고
각각이 어떤 건지 알려주자
User_first라는 변수는 methods에서 선언되지 않고 data에서 선언되었기 때문에
⇒ this. 를 이용해서 데려온다
⇒ data[0].UserID,...와 같이 각각의 인스턴스에 값을 입력
그러면,
성공!
myTable.vue 전체코드
더보기
<template> <div> <table> <thead> <tr> <th colspan="2">DB info 보기</th> </tr> </thead> <tbody> <tr> <td>UserID</td> <td>Country</td> </tr> <tr> <td>{{ UserID_first }}</td> <td>{{ Country_first }}</td> </tr> <tr> <td>{{ UserID_second }}</td> <td>{{ Country_second }}</td> </tr> </tbody> </table> </div> </template> <script> import axios from "axios"; export default { name: "myTable", data() { return { UserID_first:'', UserID_second:'', Country_first:'', Country_second:'' }; }, mounted() { this.getData(); }, methods: { async getData() { try { const { data } = await axios.get( "http://localhost:4003/api/v1/infos/get" ); //console.log(data) this.UserID_first = data[0].UserID; this.UserID_second = data[0].Country; this.Country_first = data[1].UserID; this.Country_second = data[1].Country; } catch (error) { console.err(error); } }, }, }; </script> <style> table, td { border: 1px solid #333; } thead, tfoot { background-color: #333; color: #fff; } </style>
그런데,
이렇게 mustache에 각각 넣어주는 건 데이터가 적은 지금에야 가능하다
그러니 v-for 를 이용해서 한번에 진행해보자