How to correctly use Vue JS watch with lodash debounce

29,587

Your watch should look like this.

watch: {
    searchStr: _.debounce(function(newVal){
      this.checkSearchStr(newVal)
    }, 100)
},

This is a bit unusual, however. I don't see why you would want to debounce a watch. Possibly you would rather just debounce the checkSearchStr method.

watch: {
    searchStr(newVal){
      this.checkSearchStr(newVal)
    }
},

methods: {
    checkSearchStr: _.debounce(function(string) {
        console.log(this.foo) 
        console.log(this.$store.dispatch('someMethod',string)) 
    }, 100)
}

One other thing I would like to point out; no where in the code is searchStr defined. When you watch a value with Vue, you are watching a data or computed property. As you have currently defined it, the watch on searchStr will never execute.

Share:
29,587
Artur Grigio
Author by

Artur Grigio

"A Grigio always makes the deadline!" House Grigio

Updated on July 12, 2022

Comments

  • Artur Grigio
    Artur Grigio almost 2 years

    I'm using lodash to call a debounce function on a component like so:

    ...
    import _ from 'lodash';
    
    export default {
        store,
        data: () => {
            return {
                foo: "",
            }
        },
    
        watch: {
            searchStr: _.debounce(this.default.methods.checkSearchStr(str), 100)
        },
    
        methods: {
            checkSearchStr(string) {
                console.log(this.foo) // <-- ISSUE 1
                console.log(this.$store.dispatch('someMethod',string) // <-- ISSUE 2
            }
        }
    }
    
    • Issue 1 is that my method checkSearchStr doesn't know about foo
    • Issue 2 is that my store is undefined as well

    Why doesn't my method know this when called through _.debounce? And what is the correct usage?

  • rogeriolino
    rogeriolino almost 7 years
    I think that the this (this.foo) inside the function isnt the VueJS.
  • Bert
    Bert almost 7 years
    @rogeriolino Thats not correct. When a component is instantiated, the method is bound to the component. In other words, this will be the Vue.
  • Artur Grigio
    Artur Grigio almost 7 years
    I just found the Vue.js documentation for debounce (docs - vuejs.org/v2/guide/…). Thanks for your answer (part 2), it was very helpful. I should not be running debounce on the watched element.
  • Hiep
    Hiep almost 6 years
    hmm.. I think the code can be shorter: watch: { searchStr: "checkSearchStr" } source: youtube.com/…
  • Bert
    Bert almost 6 years
    @Hiep Sure, that is documented in the API. vuejs.org/v2/api/#watch
  • Cas Bloem
    Cas Bloem over 5 years
    Just make the 'fetch data' function debounce. Cuz thats where u wanna take the load of.