vue.jsvuejs2debouncing

How to implement debounce in Vue2?


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.


Solution

  • I am using debounce NPM package and implemented like this:

    <input @input="debounceInput">
    
    methods: {
        debounceInput: debounce(function (e) {
          this.$store.dispatch('updateInput', e.target.value)
        }, config.debouncers.default)
    }
    

    Using lodash and the example in the question, the implementation looks like this:

    <input v-on:input="debounceInput">
    
    methods: {
      debounceInput: _.debounce(function (e) {
        this.filterKey = e.target.value;
      }, 500)
    }