如何导入具有正确类型的 Vue 类组件? [英] How can I import a Vue class component with proper types?

查看:26
本文介绍了如何导入具有正确类型的 Vue 类组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个单文件的 Vue 类组件,例如:

If I have a single-file Vue class component, for instance:

// MyComponent.vue
<template>
  <div></div>
</template>

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
})
export default class MyComponent extends Vue {
  public message: string = 'Hello!'
}

然后我将它导入到其他地方,并获取它的一个实例.

And I import it somewhere else, and get an instance of it.

import MyComponent from "./MyComponent.vue";
...
const foo = ... as MyComponent;
foo.message = "goodbye";

使用标准的 Vue CLI 3 设置会出现错误,因为它包含具有以下内容的 shims-vue.d.ts:

With a standard Vue CLI 3 setup this gives an error, because it contains shims-vue.d.ts with the following content:

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

据我所知,这意味着每当您编写 import Foo from "./Foo.vue" 时,Foo 将只是 的别名Vue,您将无法访问其成员.

As I understand it, this means that whenever you write import Foo from "./Foo.vue", then Foo will just be an alias for Vue, and you won't be able to access its members.

如果您从 .ts 文件导入,情况似乎确实如此.如果你从 .vue 文件导入,它会神奇地工作!

This does appear to be the case if you import from .ts files. If you import from .vue files, it magically works!

不幸的是,我所有的测试都是 .spec.ts 文件,所以我无法导入任何组件的类型.这使得测试变得困难.有什么办法可以解决这个问题吗?

Unfortunately all of my tests are .spec.ts files so I can't import the types of any components. This makes testing difficult. Is there any way to fix this?

推荐答案

我在 Vue 2 和 Vue 3 项目中的做法如下:

The way I do it in my Vue 2 and Vue 3 projects is as follows:

  1. 创建一个 Foo.vue 文件并将脚本标签添加到 Foo.vue.ts 文件中.这是片段.

  1. Create a Foo.vue file and add script tag to the Foo.vue.ts file. Here is snippet.

<template>
   <div>... Your template code here ...</div>
</template>

<script lang="ts" src="./Foo.vue.ts" />

  • 在 Foo.vue.ts 文件中编写组件代码.

  • Write component code in Foo.vue.ts file.

    import Vue from 'vue'
    import Component from 'vue-class-component'
    
    @Component({
    })
    export default class MyComponent extends Vue {
      public message: string = 'Hello!'
    }
    

    1. 现在您可以使用 as 关键字.

    import MyComponent from "./MyComponent.vue";
    ...
    const foo = obj as MyComponent;
    foo.message = "goodbye";
    

    这篇关于如何导入具有正确类型的 Vue 类组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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