【问题标题】:How to get typescript method callback working in VueJs?如何让打字稿方法回调在 VueJs 中工作?
【发布时间】:2018-11-28 13:24:27
【问题描述】:

我正在使用 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), 如果有人可以帮助我解决此错误,将不胜感激。

【问题讨论】:

标签: typescript vue.js vuejs2 typescript-typings


【解决方案1】:

这根本不可能。类型信息在 debounce 函数创建的闭包之间丢失。使用 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

【讨论】:

  • 非常感谢。根据您的建议,我能够使其正常工作。另一个相关的问题。在上面的例子中,我将参数'e'定义为'any'类型,虽然我从console.log知道,它是InputEvent类型。但不知道如何导入 InputEvent 类型。如何找到并导入合适的类型类?
  • @Raja,我也有同样的问题。这是将回答这个问题的线程。 stackoverflow.com/questions/49714315/…
  • 这种情况下updateWithDebounce: debounce(function(this: any, e: any)真的没有办法输入this吗?
猜你喜欢
  • 2012-11-09
  • 2019-08-25
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 2020-05-30
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多