How to implement debounce in Vue2?

前端 未结 13 594
梦谈多话
梦谈多话 2020-11-27 11:08

I have a simple input box in a Vue template and I would like to use debounce more or less like this:



        
相关标签:
13条回答
  • 2020-11-27 11:44

    Assigning debounce in methods can be trouble. So instead of this:

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

    You may try:

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

    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:

    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>

    0 讨论(0)
提交回复
热议问题