Skip to content

Instantly share code, notes, and snippets.

@sorie
Created March 29, 2019 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorie/ce7082534ecc2cf50ae655fa241e1d72 to your computer and use it in GitHub Desktop.
Save sorie/ce7082534ecc2cf50ae655fa241e1d72 to your computer and use it in GitHub Desktop.
vue.js에서의 watch속성을 이용하여 watch의 장점인 긴시간 비동기 처리의 예인 외부서버와의 통신 기능을 다음과 같이 해보았다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="list">
<p>
name : <input type="text" v-model="name" placeholder="두자 이상 입력하세요">
</p>
<table>
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>전화번호</th>
<th>주소</th>
<th>사진</th>
</tr>
</thead>
<tbody id="contacts">
<tr v-for="contact in contactlist">
<td>{{contact.no}}</td>
<td>{{contact.name}}</td>
<td>{{contact.tel}}</td>
<td>{{contact.address}}</td>
<td><img src="`{{contact.photo}}`" alt="{{contact.name}}"></td>
</tr>
</tbody>
</table>
<div v-show="isProcessing === true">조회중</div>
</div>
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.4/fetch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-promise/4.1.1/es6-promise.auto.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js"></script>
<script type="text/babel">
new Vue({
el: "#list",
data: {
name: "",
isProcessing: false,
contactlist: []
},
watch: {
name: function(val){
if(val.length >= 2) {
this.fetchContacts()
}else{
this.contactlist = []
}
}
},
methods:{
fetchContacts: _.debounce(function() {
this.contactlist = []
this.isProcessing = true
var url = "http://sample.bmaster.kro.kr/contacts_long/search/"+this.name
var vm = this
console.log(url)
fetch(url)
.then(function(response){
return response.json()
}).then(function(json){
vm.contactlist = json
vm.isProcessing = false
}).catch(function(ex){
console.log('parsing failed', ex)
vm.contactlist = []
vm.isProcessing = false
})
},300)
}
})
</script>
<style type="text/css">
html{font-size:16px}
#list { width: 600px; 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}
[v-clock] { display: none; }
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment