Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Created May 6, 2017 06:50
Show Gist options
  • Save TravisMullen/790a9e9f34068e4cf6a8f0ab01684bbf to your computer and use it in GitHub Desktop.
Save TravisMullen/790a9e9f34068e4cf6a8f0ab01684bbf to your computer and use it in GitHub Desktop.
debounce function for Vuejs from Docs
// https://vuejs.org/v2/guide/migration.html#debounce-Param-Attribute-for-v-model-removed
/*
By using the debounce function from lodash or another dedicated
utility library, we know the specific debounce implementation we
use will be best-in-class - and we can use it ANYWHERE. Not just
in our template.
*/
new Vue({
el: '#debounce-search-demo',
template: `<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
<div id="debounce-search-demo">
<input v-model="searchQuery" placeholder="Type something">
<strong>{{ searchIndicator }}</strong>
</div>`,
data: {
searchQuery: '',
searchQueryIsDirty: false,
isCalculating: false
},
computed: {
searchIndicator: function () {
if (this.isCalculating) {
return '⟳ Fetching new results'
} else if (this.searchQueryIsDirty) {
return '... Typing'
} else {
return '✓ Done'
}
}
},
watch: {
searchQuery: function () {
this.searchQueryIsDirty = true
this.expensiveOperation()
}
},
methods: {
// This is where the debounce actually belongs.
expensiveOperation: _.debounce(function () {
this.isCalculating = true
setTimeout(function () {
this.isCalculating = false
this.searchQueryIsDirty = false
}.bind(this), 1000)
}, 500)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment