如何让打字稿方法回调在 VueJs 中工作?

Raj*_*aja 2 typescript vue.js typescript-typings vuejs2

我正在使用 typescript 使用 vuejs 进行开发,并面临方法回调工作的问题。我基本上是在尝试通过将数据包装在 debounce 函数中来更新我的数据。我正在使用https://www.npmjs.com/package/ts-debounce模块中的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;
        },
    }
Run Code Online (Sandbox Code Playgroud)

此代码在功能上有效,但因编译错误而失败:

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

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

Har*_*til 5

这根本不可能。类型信息在 debounce 函数创建的闭包之间丢失。使用 Vue,this上下文被计算为一个组合实例。目前,无法将其正确传递给 debounce 函数。

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

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),
}
Run Code Online (Sandbox Code Playgroud)

其次,您可以使用箭头功能,这将保留键入信息:

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)();
    },
}
Run Code Online (Sandbox Code Playgroud)

然而,这显然是低效的。

另外,我不建议您以这种方式使用去抖动。想象一下,你有一个延迟为 的去抖动函数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() {

    }
}
Run Code Online (Sandbox Code Playgroud)

构建自己的 debouncer 并不难:https : //github.com/bvaughn/debounce-decorator