Debounce Computed Properties in Vue
The following approach can be used to debounce user input that triggers the rendering of vuejs computed properties. When needed, debouncing will increase site performance and improve feature usability. In the example below a dataset is being filtered and the results are interactively shown in a table. The computation happens only once exactly 250 ms after the user stops typing in the input field. Debouncing of a computed property can be achieved by watching a proxy variable (queryTableBuffer
in this case) or with the computed property's getter / setter methods.
<template lang="pug">
section.section
b-field
b-input(v-model="queryTableBuffer")
b-table(:data="queryTableResults")
</template>
<script>
import { debounce } from 'lodash'
export default {
data() {
return {
table: [],
queryTable: '',
queryTableBuffer: ''
}
},
computed: {
queryTableResults() {
return extFilteredAndSortedArray(this.table, this.queryTable)
}
},
watch: {
queryTableBuffer: debounce(function (newVal) {
this.queryTable = newVal
}, 250)
},
created() {
this.generateTable()
},
methods: {
generateTable() {
this.table = extGetDataset()
}
}
}
</script>