How to properly use Vue JS clock with lodash debounce
I am using lodash to call a debounce function on a component like this:
...
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
}
}
}
- Problem 1 is that my method
checkSearchStr
doesn't know aboutfoo
- Problem 2 is that my store
undefined
also
Why doesn't my method know this
when called through _.debounce
? And what is the correct usage?
source to share
Your watch should look like this.
watch: {
searchStr: _.debounce(function(newVal){
this.checkSearchStr(newVal)
}, 100)
},
This is a bit unusual. I don't understand why you would like to give up the watch. You might be better off just abandoning the method checkSearchStr
.
watch: {
searchStr(newVal){
this.checkSearchStr(newVal)
}
},
methods: {
checkSearchStr: _.debounce(function(string) {
console.log(this.foo)
console.log(this.$store.dispatch('someMethod',string))
}, 100)
}
One more thing I would like to point out; no where in the code is searchStr
defined. When you look at a value with Vue, you are looking at a data or computed property. Since you have currently defined it, the clock searchStr
will never run.
source to share