Skip to content

Instantly share code, notes, and snippets.

@ifranco88
Last active February 18, 2020 15:56
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 ifranco88/17bd9e01bea4aaac93c40398f74560fc to your computer and use it in GitHub Desktop.
Save ifranco88/17bd9e01bea4aaac93c40398f74560fc to your computer and use it in GitHub Desktop.
A simple vue component for input typing with delay.
<template>
<vue-input-typer placeholder="Type here" class="form-control" @typed="typedInput"></vue-input-typer>
</template>
<script>
import VueInputTyper from '@/components/input-typer.vue';
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
export default {
data: function(){
return {
xhrSearchRequest: null,
searchResult: []
};
},
methods: {
typedInput: function(text){
this.sendSearchRequest(text);
},
sendSearchRequest: function(text){
if (this.xhrSearchRequest && !this.xhrSearchRequest.isResolved)
source.cancel('Operation canceled by the user.');
this.xhrSearchRequest = axios.get('https://api.github.com/search/users?q=' + text, { cancelToken: source.token })
.then(response => {
this.searchResult = response.data.items;
console.log(this.searchResult);
});
}
},
components: {
'vue-input-typer': VueInputTyper
}
};
</script>
<!--
Sources:
https://medium.com/@umaams/searching-query-after-typing-text-on-vuejs-dd48fcfc506f
https://gist.github.com/beaucharman/1f93fdd7c72860736643d1ab274fee1a#gistcomment-2994421
-->
<template>
<input type="text" @input="isTyping = true" v-model="typedText" />
</template>
<script>
/**
* Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called.
*
* @param {*} fn
* @param {*} wait
*/
function debounce(fn, wait) {
let t;
return function () {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, arguments), wait);
};
};
export default {
props: {
},
data: function(){
return {
typedText: "",
isTyping: false,
};
},
watch: {
typedText: debounce(function() {
this.isTyping = false;
}, 1000),
isTyping: function(value) {
if (!value)
this.$emit('typed', this.typedText);
}
},
methods: {
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment