How to correctly use Vue JS watch with lodash debounce How to correctly use Vue JS watch with lodash debounce vue.js vue.js

How to correctly use Vue JS watch with lodash debounce


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.


As @Bert mentioned in comments this scope is local to the function. Therefore, to make this scope to properties in data, change to:

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