在VueJS(Javascript(中,我可以这样做:
import debounce from "lodash/debounce";
...
watch: {
variable: debounce(function() {
console.log('wow');
}, 500)
}
在VueJS(打字稿(中,我尝试:
npm i lodash-es
npm i @types/lodash-es -D
在组件中:
import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";
...
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
但是我收到错误:
缺少返回类型- 注释的"Debounce"隐式具有"any"返回类型。
- 成员"500"隐式具有"任意"类型。
附言这工作正常:
func = debounce(() => {
console.log('wow');
}, 500)
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
不是正确的语法。装饰器应该应用于类成员,但没有指定名称。
没有直接的方法可以将 Lodashdebounce
与Watch
装饰器一起使用,因为后者应该与原型方法一起使用。
可以使其成为装饰器并链接它们,但这可能会导致不良行为,因为去抖间隔将通过原型方法在所有组件实例之间共享:
function Debounce(delay: number) {
return (target: any, prop: string) => {
return {
configurable: true,
enumerable: false,
value: debounce(target[prop], delay)
};
}
}
...
@Watch('variable')
@Debounce(500)
onVariable() { ... }
...
这应该通过去抖动实例方法来实现,类似于文档建议的方式:
...
created() {
this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}
@Watch('count')
onVariable() {
this.onDebouncedVariable();
}
onDebouncedVariable() { ... }
...
你可以使用这个: https://www.npmjs.com/package/vue-debounce-decorator
然后这样做:
@Watch('value')
@Debounce(300)
private onValueChanged (val: string): void {
// do your thing here
}