【问题标题】:Vue lifecycle hook typescript error when invoking method调用方法时Vue生命周期挂钩打字稿错误
【发布时间】:2019-07-09 18:42:49
【问题描述】:

我在 typescript 的生命周期方法中引用 Vue 根组件中的方法时遇到问题。我已经能够通过下面的玩具示例重现此行为:

import Vue from "vue";

class Game {
    a: number;
    b: number;
    constructor() {
        this.a = 3;
        this.b = 4;
    }
}

new Vue({
    el: "#calculator",
    data: {
        game: null
    },
    methods: {
        // bound to a button
        reset: function() {
            this.game = new Game();
        },
        // bound to a button
        add: function() {
            this.game.a += 1;
        }
    },
    beforeCreate() {
        this.reset();
    }
});

我收到以下打字稿编译错误:

src/test.ts:28:8 - 错误 TS2339:属性“重置”不存在 输入“Vue”。

28 this.reset();

我的 IDE 告诉我 typescript 仅将data 中定义的属性解释为this 的一部分,而不是methods 中定义的属性。有没有其他人遇到过这个问题,如果有,你做了什么来解决它?

请注意,这在 javascript 中可以正常工作

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    考虑到这已经过去了几个星期,无论您是否已经自己解决了这个问题:

    由于您使用的是 TypeScript,因此您无需在“方法”对象中定义方法。您可以直接在类上定义它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2017-12-25
      • 2017-01-02
      • 1970-01-01
      • 2021-09-19
      • 2016-09-16
      • 2019-01-17
      相关资源
      最近更新 更多