如何在带有Typescript的VueJs手表中使用Lodash防反跳

时间:2019-09-04 13:43:58

标签: typescript vue.js lodash watch

在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'隐式具有'any'类型。

P.S。效果很好:

func = debounce(() => {
    console.log('wow');
}, 500)

2 个答案:

答案 0 :(得分:2)

@Watch("variable")
debounce(function() {
  console.log('wow');
}, 500)

语法不正确。装饰器应该应用于类成员,但未指定名称。

没有将Lodash debounceWatch装饰器结合使用的直接方法,因为后者应该与原型方法一起使用。

有可能使其成为装饰器并将它们链接起来,但这可能会导致不良行为,因为去抖动间隔将通过原型方法在所有组件实例之间共享:

function Debounce(delay: number) {
  return (target: any, prop: string) => {
    return {
        configurable: true,
        enumerable: false,
        value: debounce(target[prop], delay)
    };
  }
}

...
@Watch('variable')
@Debounce(500)
onVariable() { ... }
...

这可能应该通过取消实例方法来实现,类似于the documentation的建议:

...
created() {
  this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}

@Watch('count')
onVariable() {
    this.onDebouncedVariable();
}

onDebouncedVariable() { ... }
...

答案 1 :(得分:0)

您可以使用:https://www.npmjs.com/package/vue-debounce-decorator

然后执行以下操作:

  @Watch('value')
  @Debounce(300)
  private onValueChanged (val: string): void {
    // do your thing here
  }