How to implement debounce in Vue2 ?

How to implement debounce in Vue2 ?

Asked on November 22, 2018 in vue.js.
Add Comment


  • 2 Answer(s)

    This solution is executed with the help of NPM package:

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

    With the help of lodash, it is executed as follows:

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

    Using debounce in functions will lead to problem. As an alternative for this:

    // Bad
    methods: {
      foo: _.debounce(function(){}, 1000)
    }
    

    You might attempt:

    // Good
    created () {
      this.foo = _.debounce(function(){}, 1000);
    }
    

    Suppose, if you are utilizing several cases of element, it creates problem. Similarly, the path of information must be a method which returns item. Every case wants its individual debounce method if it wants to perform autonomously.

    Sample for this problem:

    Vue.component('counter', {
      template: '<div>{{ i }}</div>',
      data: function(){
        return { i: 0 };
      },
      methods: {
        // DON'T DO THIS
        increment: _.debounce(function(){
          this.i += 1;
        }, 1000)
      }
    });
     
     
    new Vue({
      el: '#app',
      mounted () {
        this.$refs.counter1.increment();
        this.$refs.counter2.increment();
      }
    });
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
     
    <div id="app">
      <div>Both should change from 0 to 1:</div>
      <counter ref="counter1"></counter>
      <counter ref="counter2"></counter>
    </div>
    
    Answered on November 22, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.