如何在带有Typescript的VueJs手表中使用Lodash防反跳 [英] How to use Lodash debounce in VueJs watch with Typescript
问题描述
在VueJS(Java语言)中,我可以这样做:
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'隐式具有'any'类型.
- 'debounce', which lacks return-type annotation, implicitly has an 'any' return type.
- Member '500' implicitly has an 'any' type.
P.S.效果很好:
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.
没有直接的方法将Lodash的 debounce
与 Watch
装饰器一起使用,因为后者应该与原型方法一起使用.
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() { ... }
...
这篇关于如何在带有Typescript的VueJs手表中使用Lodash防反跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!