简体   繁体   English

在纯 TypeScript 文件中导入 Vue 组件失败

[英]Import Vue component in plain TypeScript file fails

I have a Vue project in which I created a new and plain TypeScript file Validation.ts :我有一个 Vue 项目,我在其中创建了一个新的普通 TypeScript 文件Validation.ts

import Vue from 'vue';
import BaseInput from '@/components/base/BaseInput.vue';

class ValidationService extends Vue {
  validateFields(fields: BaseInput[]): boolean {
    return this.$store.state.skipValidation || fields.map(field => field.validate()).every(Boolean);
  }
}

export default new ValidationService();

My class BaseInput has the public method validate() (which I'm able to call successfully from within other Vue components).我的类BaseInput有公共方法validate() (我可以从其他 Vue 组件中成功调用它)。 But TypeScript now complains because it can't find the BaseInput class.但是 TypeScript 现在抱怨,因为它找不到BaseInput类。 When I try to follow the import I end up in the shims-vue.d.ts file.当我尝试遵循导入时,我最终出现在shims-vue.d.ts文件中。

How can I properly import a Vue component from outside a .vue file?如何从.vue文件外部正确导入 Vue 组件? Or is there a better solution to provide Vue with some global TypeScript methods then defining them in a plain .ts file?或者是否有更好的解决方案为 Vue 提供一些全局 TypeScript 方法,然后在一个普通的.ts文件中定义它们?

A .vue file contains a lot of things : a template part, a script part and a style part ... and typescript don't know how to handle that. .vue文件包含很多东西:模板部分、脚本部分和样式部分……而 typescript 不知道如何处理。 A component is not made to be imported in a service, it's made to display/render something and it's definitely not made to define a type.组件不是为了在服务中导入而设计的,它是用来显示/渲染某些东西的,绝对不是用来定义类型的。

What you need to define a type or an interface in a separate file let' say ./models/input.ts where you can define your inputs types在单独的文件中定义类型或接口需要什么,比如./models/input.ts ,您可以在其中定义输入类型

export interface IBaseInput {
    name: string;
    ...
    ...
}
export interface IComplexInput {
    name: string;
    ...
    ...
}

I like to prefix my interfaces with an "I", but some people say you shouldn't (that's up to you)我喜欢在我的接口前加上“I”,但有些人说你不应该(这取决于你)

then in your component .vue然后在你的组件.vue

import { IBaseInput } from './models/input.ts'
class BaseInput extends Vue implements IBaseInput {
    ...
}

and in your Service并在您的服务中

import { IBaseInput } from './models/input.ts'
class ValidationService extends Vue {
  validateFields(fields: IBaseInput[]): boolean {
    return this.$store.state.skipValidation || fields.map(field => field.validate()).every(Boolean);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM