【问题标题】:Errors compiling Vue with TypeScript使用 TypeScript 编译 Vue 时出错
【发布时间】:2019-08-01 04:53:29
【问题描述】:

在带有 TypeScript 的 Vue 中多次使用带有模板的组件

我的目标是在另一个组件中多次使用带有模板的组件。 代码在 .html 和 .ts 文件中分开。

.html 看起来像这样:

<template>
    <div id="app">
        <inner-component></inner-component>
        <hr />
        <inner-component></inner-component>
        <hr />
        <inner-component></inner-component>
    </div>
</template>

<script src="./componenttest.ts"></script>

虽然 .ts 是这样的:

import Vue from 'vue';
import { Component } from 'vue-property-decorator';

export interface IStatus extends Vue {
    status: string;
}

var InnerComponent = Vue.extend({
    template: '<p>Server Status: {{ status }}(<button @click="changeStatus">Change</button>)</p>'
})

@Component({
    data: function (): IStatus {
        return { status: 'Critical'}
    },
    components: { InnerComponent },
    methods: {
        changeStatus: function (): void {
            this.status = 'Normal';
        }
    }
})
export default class ComponentTestComponent extends Vue {
}

运行项目会导致以下错误消息:

[at-loader] TS2322 中的错误:类型 '{ status: string; }' 不可分配给类型 'IStatus'。

[at-loader] TS2322 中的错误:类型 '{ status: string; }' 不可分配给类型 'IStatus'。 '{ status: string; 类型中缺少属性 '$data' }'。

[at-loader] TS2339 中的错误:“Vue”类型上不存在属性“状态”。

如果我删除数据标签中的 IStatus 接口标记,我得到的唯一错误消息是:

[at-loader] TS2339 中的错误:“Vue”类型上不存在属性“状态”。

我尝试在ComponentTestComponent中实现我的接口,但错误依旧。

我的猜测是,界面缺少一些细节,所以 TypeScript 不会生成它。最终 Vue 实例因此无法访问 status 属性。

【问题讨论】:

  • 不要将@Component 对象用于应该在类定义中的东西(data 和methods)。
  • 感谢您的建议,我会记住这一点,但主要问题是此错误消息: [at-loader] TS2339 中的错误:“Vue”类型上不存在属性“状态” .

标签: typescript vue.js vue-component


【解决方案1】:

发生编译错误是因为IStatus 接口正在扩展Vue 并且Vue 接口需要的不仅仅是“状态”属性。

试试这个:

export interface IStatus {
    status: string;
}

【讨论】:

  • 是的,没错,这是我创建界面的第一种方式。但主要错误消息仍然存在:[at-loader] TS2339 中的错误:“Vue”类型上不存在属性“状态”。
【解决方案2】:

好像缺少这段代码:

declare module 'vue/types/vue' {
    interface Vue {
        status: string
    }
}

这是使用附加属性扩展 Vue 实例所必需的。

说实话,文档中包含此内容,只是我不确定此场景的用法。

https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins

【讨论】:

    【解决方案3】:

    如果有人还在苦苦挣扎,请使用 vue cli 而不是手动创建和导入商店

    npx @vue/cli 添加 vuex

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-11
      • 2021-05-27
      • 1970-01-01
      • 2017-10-04
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多