在 VueJS (Javascript) 中我可以这样做:
import debounce from "lodash/debounce";
...
watch: {
variable: debounce(function() {
console.log('wow');
}, 500)
}
在 VueJS (Typescript) 中我尝试:
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”类型。
附:这工作正常:
func = debounce(() => {
console.log('wow');
}, 500)
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
不是正确的语法。装饰器应该应用于类成员,但未指定名称。
使用 Lodash 没有直接的方法debounce
with 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() { ... }
...
这可能应该通过去抖动实例方法来实现,类似于文档 https://v2.vuejs.org/v2/guide/computed.html#Watchers建议:
...
created() {
this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}
@Watch('count')
onVariable() {
this.onDebouncedVariable();
}
onDebouncedVariable() { ... }
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)