使用TypeScript

时间:2019-03-10 20:53:25

标签: typescript vue.js vue-component

在具有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 {
}

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

  

[加载器] TS2322中的错误:键入'{状态:字符串; }”不能分配给“ IStatus”类型。

     

[加载器] TS2322中的错误:键入'{状态:字符串; }”不可分配给“ IStatus”类型。         类型'{status:string;类型中缺少属性'$ data' }'。

     

[加载器] TS2339中的错误:类型'Vue'不存在属性'status'。

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

  

[加载器] TS2339中的错误:类型'Vue'不存在属性'status'。

我尝试在ComponentTestComponent中实现我的接口,但错误仍然相同。

我的猜测是,该接口缺少一些细节,因此TypeScript不会生成它。最后,由于这个原因,Vue实例无法到达status属性。

1 个答案:

答案 0 :(得分:0)

似乎缺少这段代码:

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

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

说实话,文档中包含此内容,只是我不确定这种情况的用法。

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