Search code examples
javascriptvue.jslodash

What is wrong with Vue and lodash debounce?


The props:

props: {
  delay: Number,
}

The watcher:

 watch: {
   q: _.debounce(function() {
     console.log(this.delay);      // 500; always works fine, this.delay is here
   }, this.delay)                  // never works; 
 },

If hardcode a delay (set 500 instead of this.delay - it works; otherwise - function not debounce).

What am I doing wrong? Thanks.


Solution

  • You won't be able to accomplish setting the delay there. this is not the component in that scope. You can use $watch instead inside a lifecycle hook:

    created () {
      this.debounceUnwatch = this.$watch('q', _.debounce(
        this.someMethod,
        this.delay
      ))
    },
    
    destroyed () {
      // Removed the watcher.
      this.debounceUnwatch()
    },
    

    For more information: https://v2.vuejs.org/v2/api/#vm-watch

    Edit

    This doesn't work either. It just really seemed like it should have. What I think needs to be done here is you need to debounce whatever is updating q and not q itself.