vue를 통해 ajax 데이터를 가져와서 로딩하기
- 처리 프로세스
1) vue 객체 안에 ajax를 호출하는 메서드를 선언한다.
2) 이 메서드 안의 url 요청값으로 json 데이터를 출력하는 controller를 호출한다.
3) 이 json 데이터를 vue 객체의 모델 데이터에 할당하여 화면에 출력한다.
var vm = new Vue({
el:".container",
data:{msg:"ajax부서정보",dname:"",loc:"",dlist:[]},
methods:{
callAjax:function(){
// vue 모델데이터 초기화
this.dlist=[]
// json 데이터를 받아올 controller get 방식으로 호출
var url="/springweb/deptAjaxVue.do?dname="+this.dname+"&loc="+this.loc
// Vue 객체의 다른 속성(모델,메서드)를 fetch api 안에서 사용하기 위해 선언
var vm = this;
// fetch api 를 통해 response 객체 가져오기
fetch(url).then(function(response){
return response.json()
// json 데이터 가져오기
}).then(function(json){
// vue 객체의 모델데이터에 json 데이터 할당
vm.dlist = json.dlist
}).catch(function(err){
console.log(err) // 에러 표시
})
}
}
});
<form id="frm01" class="form-inline" method="post">
// 엔터키 눌렀을 때 fetchList 메서드 실행
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<input @keyup.13="callAjax" v-model="dname" class="form-control mr-sm-2" placeholder="부서명" />
<input @keyup.13="callAjax" v-model="loc" class="form-control mr-sm-2" placeholder="부서위치" />
// 버튼 클릭시 fetchList 메서드 실행
<button @click="fetchList" class="btn btn-info" type="button">Search</button>
</nav>
</form>
// json 데이터 반복문을 통해 출력
<tbody>
<tr v-for="d in dlist">
<td>{{d.deptno}}</td><td>{{d.dname}}</td><td>{{d.loc}}</td></tr>
</tbody>