Vad*_*lev 5 watch typescript lodash vue.js
在 VueJS (Javascript) 中,我可以这样做:
import debounce from "lodash/debounce";
...
watch: {
variable: debounce(function() {
console.log('wow');
}, 500)
}
Run Code Online (Sandbox Code Playgroud)
在 VueJS (Typescript) 中,我尝试:
npm i lodash-es
npm i @types/lodash-es -D
Run Code Online (Sandbox Code Playgroud)
在组件中:
import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";
...
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
PS 这工作正常:
func = debounce(() => {
console.log('wow');
}, 500)
Run Code Online (Sandbox Code Playgroud)
Est*_*ask 10
@Watch("variable")
debounce(function() {
console.log('wow');
}, 500)
Run Code Online (Sandbox Code Playgroud)
不是正确的语法。装饰器应该应用于类成员,但没有指定名称。
没有直接的方法可以将 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() { ... }
...
Run Code Online (Sandbox Code Playgroud)
这可能应该通过 debounce 实例方法来实现,类似于文档建议的方式:
...
created() {
this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}
@Watch('count')
onVariable() {
this.onDebouncedVariable();
}
onDebouncedVariable() { ... }
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5377 次 |
| 最近记录: |