I have a simple input box in a Vue template and I would like to use debounce more or less like this:
<input type="text" v-model="filterKey" debounce="500">
However the debounce
property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".
How do you correctly implement it?
I've tried to implement it using lodash, v-on:input and v-model, but I am wondering if it is possible to do without the extra variable.
In template:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
In script:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
The filterkey is then used later in computed
props.
If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce
Usage:
Then in your component:
Assigning debounce in
methods
can be trouble. So instead of this:You may try:
It becomes an issue if you have multiple instances of a component - similar to the way
data
should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.Here's an example of the problem:
Based on comments and the linked migration document, I've made a few changes to the code:
In template:
In script:
And the method that sets the filter key stays the same:
This looks like there is one less call (just the
v-model
, and not thev-on:input
).short and sweet:
helpers.js
.vue
(credit to tiny debounce)
I am using debounce NPM package and implemented like this:
Using lodash and the example in the question, the implementation looks like this:
I had the same problem and this worked without plugins.
Since
<input v-model="xxxx">
is the same as(source)
I figured I could set a debounce function on the assigning of xxxx in
xxxx = $event.target.value
like this
methods: