In VueJS (Javascript) I can do this:
import debounce from "lodash/debounce";
...
watch: {
variable: debounce(function() {
console.log('wow');
}, 500)
}
In VueJS (Typescript) I try:
npm i lodash-es
npm i @types/lodash-es -D
In component:
import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";
...
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
But I get errors:
P.S. This works fine:
func = debounce(() => {
console.log('wow');
}, 500)
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
isn't a correct syntax. A decorator is supposed to be applied to class member but no name was specified.
There's no straightforward way to use Lodash debounce
with Watch
decorator because the latter is supposed to be used with prototype method.
It's possible to make it a decorator and chain them but this will likely result in undesirable behaviour because debounce interval will be shared through prototype method between all component instances:
function Debounce(delay: number) {
return (target: any, prop: string) => {
return {
configurable: true,
enumerable: false,
value: debounce(target[prop], delay)
};
}
}
...
@Watch('variable')
@Debounce(500)
onVariable() { ... }
...
This likely should be achieved by debouncing instance method, similarly to how the documentation suggests:
...
created() {
this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}
@Watch('count')
onVariable() {
this.onDebouncedVariable();
}
onDebouncedVariable() { ... }
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With