【问题标题】:What is a proper way to create a type for Vue props为 Vue 道具创建类型的正确方法是什么
【发布时间】:2021-08-24 04:27:23
【问题描述】:

我正在尝试在 Vue js 中为我的道具创建一个自定义 type,我创建了一个类型文件夹并将其添加到 IntelliSense 的 tsconfig.typeRoots 中,所有其他东西都正常工作,编译时没有问题时间但是当我访问该组件时,我收到一个错误 Car is not defined 但我已经定义了它并且它在其他地方工作但是在检查官方文档后我知道该道具需要一个 constructor 所以我将类型重新定义为declare class Car 并添加了一个构造函数原型,但同样的问题。

以下是文件: 汽车部件

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "the-car",
  props: {
    car: {
      required: true,
      type: Car,
    },
  },
});
</script>

types/common/index.d.ts 声明文件

declare class Car {
    name: String;
    image: String;
    kms: Number;
    gears: String;
    desc: String;
    fuel: String;
    engine: String;
    price: Number;
    constructor(name: String, image: String, kms: Number, gears: String, desc: String, fuel: String, engine: String, price: Number);
}

【问题讨论】:

  • 您好,我认为您需要在组件中导入index.d.ts 文件。
  • @YashMaheshwari 我已经在tsconfig.json 中添加了一个条目,并且类型检查在不导入的情况下运行良好

标签: typescript vue.js nuxt.js typescript-typings vue-props


【解决方案1】:

如果您介意使用 Typescript 界面,那么您可以查看post

在你的情况下,创建Car Interface:

props: {
  car: {
    required: true,
    type: Object as () => Car,
  },
},

编辑:

作为@Chin。乌达拉提议。

如果您发现验证器没有获得类型推断或成员完成 不起作用,使用预期类型注释参数可能会有所帮助 解决这些问题。

import Vue, { PropType } from 'vue'

const Component = Vue.extend({
  props: {
    car: {
      required: true,
      type: Object as PropType<Car>,
    }
  }
})

查看来自 Vue.js 的 Typescript Support docs 了解更多信息。

【讨论】:

  • 你不应该使用PropType&lt;&gt;吗?
  • 如果我这样做了,我在编译期间不会遇到任何问题,但在运行时,对于Car 的所有成员,我会收到以下错误client.js?06a0:56 [Vue warn]: Property or method "desc" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. found in
  • 您可能想要像@Chin.Udara 建议的那样注释道具。 Check this vue js 关于 typescript 支持的文档,这可能会帮助您解决问题。
  • PropType&lt;Car&gt; 也一样,在运行时遇到问题
猜你喜欢
  • 2012-06-01
  • 2021-06-27
  • 2018-05-29
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多