如何使Typescript方法回调在VueJs中工作?

时间:2018-06-19 14:24:37

标签: typescript vue.js vuejs2 typescript-typings

我正在使用使用typescript的vuejs进行开发,并且面临方法回调工作的问题。我基本上是想通过将其包装在反跳功能中来更新数据。我正在使用https://www.npmjs.com/package/ts-debounce模块中的去抖动功能。这是代码示例:

import { debounce } from 'ts-debounce';

export default Vue.extend({
    name: 'HelloWorld',
    data() {
        return {
            input: '# hello',
        };
    },

    methods: {
        updateWithDebounce: debounce(function(e: any) {
            this.input = e.target.value;
        }, 2000),

       update(e: any) {
            this.input = e.target.value;
        },
    }

此代码可以正常工作,但会因编译错误而失败:

'this'隐式具有类型'any',因为它没有类型注释。     40 |     41 | updateWithDebounce:debounce(function(e:any){

  

42 | this.input = e.target.value;          | ^       43 | },2000),   如果有人可以帮助我解决此错误,将不胜感激。

1 个答案:

答案 0 :(得分:3)

这根本不可能。在通过反跳函数创建的闭包之间,类型信息会丢失。使用Vue,this上下文被计算为组合实例。当前,没有办法正确地将其传递给去抖动功能。

在这种情况下,您有两种选择:

methods: {
    // set this pointer to explicitly any. But you will lose typing info.
    updateWithDebounce: debounce(function(this: any, e: any) {
        this.input = e.target.value;
    }, 2000),
}

第二,您可以使用箭头功能,它将保留键入信息:

methods: {
    // set this pointer to explicitly any. This will mask your typing info though.
    updateWithDebounce() {
        // call debounced function immediately.
        debounce(() => this.input = e.target.value, 2000)();
    },
}

但是,这显然效率低下。

此外,我不建议您通过这种方式使用反跳功能。假设您以2000ms的延迟对功能进行了反跳。如果您的Vue组件在此期间被销毁,那么肯定会引起麻烦。我认为ts-debounce不了解Vue组件何时被销毁。

正确的方法是使用Rxjs流或Observables之类的反跳。或构建自己的帮助程序功能。

最后,您可以使用类语法vue-class-component并像这样构建自己的装饰器:

@Component({})
export default class SimpleComponent extends Vue {

    // Selected value of each menu item
    public someValue = 1;

    public data() {

        return {
            // Some data...
        };
    }

    @Debounce(2000)
    public updateWithDebounce() {

    }
}

构建自己的去抖动器并不是很困难:https://github.com/bvaughn/debounce-decorator