vue-class-component:调用类方法时为TS2339 [英] vue-class-component : TS2339 when calling class method

查看:563
本文介绍了vue-class-component:调用类方法时为TS2339的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用vue-cli-service构建我的vuejs应用程序.

I'm using vue-cli-service to build my vuejs application.

构建成功,但是在webstorm IDE中,出现一些TS2339错误:

The build is successful, but in webstorm IDE, I get some TS2339 errors :

Test.vue:

<template>
    <div>{{method()}}</div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';

    @Component
    export default class Test extends Vue {
        public method(): string {
            return 'hello';
        }
    }
</script>

Test.spec.ts:

import 'jest';
import {mount} from '@vue/test-utils';
import Test from '@/views/common/Test.vue';

describe('Test.vue', () => {
    let wrapper: any;

    beforeEach(() => {
        wrapper = mount(Test);
    });

    test('test method call', () => {
        const test = wrapper.find(Test).vm as Test;
        expect(test.method()).toEqual('hello');
    });
});

在Test.spec.ts中,无论是在编辑器还是在打字稿窗口中,我都收到此错误:

In Test.spec.ts, I get this error, both in editor and in typescript window:

错误:(14,21)TS2339:类型'Vue'不存在属性'method'.

Error:(14, 21) TS2339: Property 'method' does not exist on type 'Vue'.

但是测试还可以,所以test.method()在运行时可以成功解决.

But the test is OK, so test.method() is resolved successfully at runtime.

推荐答案

基于史蒂文(Steven)的回答,我知道shims-vue.d.ts对于将组件用作打字稿类是必需的.但是问题在于它们都被视为Vue实例. 在查看此文件内容时,这很明显:

Based on Steven's answer, I understood that shims-vue.d.ts is necessary to use component as typescript classes. But the problem is that they are all considered as Vue instances. This is obvious when looking at this file contents:

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}

目前,我发现的唯一干净的方法是声明一个由我的组件实现的接口:

For now, the only clean way I found is to declare an interface implemented by my component:

model.ts:

export interface ITest {
    method(): void;
}

Test.vue:

<template>
    <div>{{method()}}</div>
</template>

<script lang="ts">
    import { Component } from 'vue-property-decorator';
    import Vue from 'vue';
    import {ITest} from '@/views/test/model';

    @Component
    export default class Test extends Vue implements ITest {
        public method(): string {
            return 'hello';
        }
    }
</script>

Test.spec.ts:

import 'jest';
import {mount} from '@vue/test-utils';
import {ITest} from '@/views/test/model';
import Test from '@/views/test/Test.vue';

describe('Test.vue', () => {
    let wrapper: any;

    beforeEach(() => {
        wrapper = mount(Test);
    });

    test('test method call', () => {
        const test = wrapper.find(Test).vm as ITest;
        expect(test.method()).toEqual('hello');
    });
});

这篇关于vue-class-component:调用类方法时为TS2339的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆