Vue.js
[Vue] Vue js 비동기통기(axios) 샘플코드
dev.mk
2022. 6. 25. 15:19
반응형
axios 설치하기
프로잭트폴더에서 아래의 명령어로 설치한다.
npm install axios
main.js에 Vue.prototype.$axios = axios 를 미리 등록하면 사용하는 페이지에서 this키워드로 axios에 접근할 수 있다.
굳이 선언을 안해도 상관없다.
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import axios from "axios";
// Import Bootstrap an BootstrapVue CSS files (order is important)
// Define variable defaults
import './app.scss'
Vue.prototype.$axios = axios
Vue.config.productionTip = false
// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue)
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin)
export default
new Vue({
router,
render: h => h(App),
}).$mount('#app')
Store.vue
<template>
<div>
<div align="right" style="margin:10px">
<button type="button" class="btn btn-outline-info btn-sm" @click='writeContent()'>주문</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">종류</th>
<th scope="col">메뉴명</th>
<th scope="col">가격</th>
<th scope="col">재고</th>
</tr>
</thead>
<tbody>
<tr v-for="item in contents" v-bind:key="item.id" @click='toDetail(item.id)'>
<th scope="row">{{item.id}}</th>
<td >{{item.menu_category}}</td>
<td>{{item.menu_name}}</td>
<td>{{item.menu_price}}</td>
<td>{{item.menu_stock}}</td>
<!-- <td>{{ formatDate(item.updatedAt)}}</td> -->
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
contents: null
}
},
methods: {
toDetail(contentId){
this.$router.push({
//StoreDetail.vue 화면 이동
name: "storeDetail",
query: {id : contentId}
});
},
writeContent(){
this.$router.push({
//StoreEdit.vue 화면 이동
name: "storeEdit"
});
},
formatDate(str){
return str.split('T')[0];
},
//화면 진입시 데이터 조회 실행
fetchData(){
this.$axios.get('http://localhost:8080/menu/')
.then(res => {
console.log('매장 전체호출 성공 로그');
console.log(res.data.data.result);
//조회결과를 화면에 표시할 데이터영역에 담는다.
this.contents = res.data.data.result;
})
.catch(function(error){
console.log('전체호출 에러 로그');
console.log(error);
});
}
},
created() {
this.fetchData();
}
}
</script>
fetchData() 메소드안에 목록을 호출하는 axios 코드를 작성후 콜백인 then() 함수로 서버에서 받은 데이터를 처리한다.
created() 초기화 메소드에서 fetchData()메소드를 호출하면 화면 진입시 목록을 호출한다.
반응형