본문 바로가기
study/Vue

[Vue] 28. 외부데이터 처리하기2 (vueex5.html )

by 금이패런츠 2022. 5. 31.
728x90
반응형

vueex5.html

<!DOCTYPE html>
<!-- 
	/vue1/src/main/webapp/20220531/vueex5.html  
	
	vueex4.html과 같은 결과
-->
<html>
<head>
<meta charset="UTF-8">
<title>외부 데이터 처리하기2</title>
<script type="text/javascript" src="https:unpkg.com/vue@2.5.16/dist/vue.js"></script>
<style type="text/css">
	#list {width:400px; border:1px solid black; border-collapse:collapse;}
	#list td, #list th {border:1px solid black; text-align:center;}
	#list > thead > tr {color:yellow; background-color:purple;}
</style>
</head>
<body>
<div id="simple">
<!-- 
	v-on:keyup.13 : enter키가 눌려진 경우 발생되는 키보드 이벤트. 
			  .enter : enter키를 의미하는 별명
	vue에서 제공되는 키의 별명
		.enter, .tab, .delete, .esc, .space, .up, .down, .left, .right
		.ctrl, .alt, .shift, ...
		
	CTRL + C 키 : v-on:keyup.ctrl.67
-->
	<p>
		<input type="text" v-model="name" v-on:keyup.13="search" placeholder="두글자이상입력">
	</p>
	<table id="list">
		<thead>
			<tr>
				<th>번호</th>
				<th>이름</th>
				<th>전화번호</th>
				<th>주소</th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="contact in contactlist">
				<td>{{contact.no}}</td>
				<td>{{contact.name}}</td>
				<td>{{contact.tel}}</td>
				<td>{{contact.address}}</td>
			</tr>
		</tbody>
	</table>
	<div v-show="isProcessing === true">조회중</div>
</div>
<script>
	let model = {
			name : "",
			contactlist : [],
			isProcessing : false
	}
	
	let simple = new Vue ({
		el : "#simple",
		data : model,
		methods : {
			//enter키가 눌려진 경우 호출되는 이벤트 핸들러
			search : function(e) {
				let val = e.target.value 
				if(val.length >= 2) 
					this.fetchContacts(); 
				else
					this.contactlist=[] 
			},
			fetchContacts : function() {
				this.contactlist = []
				this.isProcessing = true
				//this.name : ko => 입력된 값
				let url = "http://sample.bmaster.kro.kr/contacts_long/search/"+this.name
				let vm = this
				//url : http://sample.bmaster.kro.kr/contacts_long/search/ko
				//fetch(url) : 외부 데이터를 조회.
				//response : url에서 전송된 응답 데이터
				fetch(url).then(function(response) {
					return response.json() //json 객체 형태로 리턴. 다음으로 전달.
				}).then(function(json) { //json : response.json() 값. json 객체
					vm.contactlist = json
					vm.isProcessing = false
				}).catch(function(ex) {
					//catch : 오류 발생시 호출되는 영역
					//ex : 예외 객체
					console.log('parsing failed', ex);
					vm.contactlist = [];
					vm.isProcessing = false;
				})
			}
		}
	})
</script>
</body>
</html>
728x90
반응형