반응형
Vuejs와 Axios가 여러 get 요구를 하다
간단한 Vue 스크립트를 사용하여 Vue를 처음 학습합니다.
<!DOCTYPE html>
<html>
<head>
<title>My first Vue app</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question" type="text">
<img v-bind:src="image">
</p>
<p>{{ answer }}</p>
</div>
<script>
let watchExample = new Vue({
// Root element of app
el : '#watch-example',
// Properties keep track of
data : {
question : '',
answer : 'I cannot give you an answer until you ask a question!',
image : '',
},
watch : {
question : function(newVal, oldVal) {
const vm = this;
vm.answer = 'Waitinng for you to stop typing.';
setTimeout(function() {
vm.getAnswer();
}, 350);
}
},
// App methods
methods : {
getAnswer: function() {
const vm = this;
if(!vm.question.includes('?')) {
vm.answer = 'Questions usually contain a question mark';
vm.image = '';
return;
}
vm.answer = 'Thinking...';
setTimeout(function() {
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = response.data.answer;
vm.image = response.data.image;
});
}, 500);
}
}
});
</script>
</body>
</html>
질문을 입력할 때 물음표가 포함되어 있는 것을 알 수 있었습니다.?)가 너무 빨라서 여러 번 요청을 하고 여러 번 응답을 받습니다.여러 개의 응답이 반환되면 이미지가 지워지고 새로운 응답이 추가됩니다.질문을 천천히 입력하면 하나의 응답만 반환됩니다.
console.log(response)에 콘솔 내의 여러 응답을 나타냅니다.
입력 속도에 관계없이 질문에 대한 답변을 하나만 받으려면 어떻게 해야 합니까?
변경 시마다 타이머를 다시 시작할 수 있습니다(즉, 현재 타이머가 있는 경우 중지한 다음 다른 타이머를 시작합니다).는 연관된 타이머 ID를 반환합니다.이 ID는 타이머를 정지하기 위해 에 전달할 수 있습니다.코드는 다음과 같습니다.
watch: {
question : function(newVal, oldVal) {
...
clearTimeout(this._timerId);
this._timerId = setTimeout(function() {
vm.getAnswer();
}, 350);
}
},
<!DOCTYPE html>
<html>
<head>
<title>My first Vue app</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question" type="text">
<img v-bind:src="image">
</p>
<p>{{ answer }}</p>
</div>
<script>
let watchExample = new Vue({
// Root element of app
el : '#watch-example',
// Properties keep track of
data : {
question : '',
answer : 'I cannot give you an answer until you ask a question!',
image : '',
},
watch : {
question : function(newVal, oldVal) {
const vm = this;
vm.answer = 'Waitinng for you to stop typing.';
clearTimeout(this._timerId);
this._timerId = setTimeout(function() {
vm.getAnswer();
}, 350);
}
},
// App methods
methods : {
getAnswer: function() {
const vm = this;
if(!vm.question.includes('?')) {
vm.answer = 'Questions usually contain a question mark';
vm.image = '';
return;
}
vm.answer = 'Thinking...';
setTimeout(function() {
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = response.data.answer;
vm.image = response.data.image;
});
}, 500);
}
}
});
</script>
</body>
</html>
여기서 필요한 건debounce부터lodash
Vue 설명서에 좋은 예가 제시되어 있습니다.
예를 들어, 다음의 코드에 주의해 주세요.
created: function () {
// _.debounce is a function provided by lodash to limit how
// often a particularly expensive operation can be run.
// In this case, we want to limit how often we access
// yesno.wtf/api, waiting until the user has completely
// finished typing before making the ajax request. To learn
// more about the _.debounce function (and its cousin
// _.throttle), visit: https://lodash.com/docs#debounce
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
현재 set Timeout으로 콜을 랩함으로써 콜을 지연시키고 있습니다.내 생각에 넌 지금 이 일을 해내려고 하는 것 같아debounce영향.
Lodash에는 이 기능이 있지만, 아직 Lodash를 사용하지 않고 프로젝트에 포함시키고 싶지 않다면 몇 줄의 코드로 쉽게 작성할 수 있습니다.
언급URL : https://stackoverflow.com/questions/55717947/vuejs-axios-make-multiple-get-requests
반응형
'source' 카테고리의 다른 글
| VueJS 컴포넌트(TypeScript)에서 "_super.apply is not function"(_super.apply is not function)을 해결하는 방법 (0) | 2022.08.27 |
|---|---|
| 16진수 부동 상수(C) (0) | 2022.08.27 |
| Vuex에서 store.subscribe() 메서드를 사용할 수 없습니다. (0) | 2022.08.27 |
| swiper/vue 종속성을 사용할 수 없습니다. (0) | 2022.08.27 |
| Element 라이브러리의 테이블 열에서 렌더 헤더 함수를 사용하는 방법 (0) | 2022.08.27 |