使用 TypeScript 在 Vue.js 3 中输入的道具

编程入门 行业动态 更新时间:2024-10-11 15:19:12
本文介绍了使用 TypeScript 在 Vue.js 3 中输入的道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用组合 API 在 Vue 3 组件中输入提示我的道具.

I'm trying to type hint my props in a Vue 3 component, with composition API.

所以,我正在这样做:

<script lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
import { ref } from 'vue';
import { useStore } from 'vuex';

export default {
    props: {
        message: {
            type: FlashInterface,
            required: true
        }
    },
    setup(props): Record<string, unknown> {
        // Stuff
    }
};

我的 FlashInterface 看起来像这样:

My FlashInterface looks like this:

export default interface FlashInterface {
    level: string,
    message: string,
    id?: string
}

这个界面运行良好,除非我遇到这个错误:

This interface works well except in this case where I got this error:

ERROR in src/components/Flash.vue:20:10
TS2693: 'FlashInterface' only refers to a type, but is being used as a value here.
    18 |    props: {
    19 |        message: {
  > 20 |            type: FlashInterface,
       |                  ^^^^^^^^^^^^^^
    21 |            required: true
    22 |        }
    23 |    },

我不明白为什么 TypeScript 认为这是一个值.

I don't understand why TypeScript thinks this is a value.

我错过了什么?

推荐答案

您应该将它与从 vue 导入的 PropType 一起使用,例如 Object as PropType::>

You should use it with PropType imported from vue like Object as PropType<FlashInterface>:

import FlashInterface from '@/interfaces/FlashInterface';
import { ref,PropType, defineComponent } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
    props: {
        message: {
            type: Object as PropType<FlashInterface>,
            required: true
        }
    },
    setup(props) {
            // Stuff
        }
});

注意:您应该使用 defineComponent 创建组件以获得类型推断.

Note : you should create your component using defineComponent in order to get the types inference.

这篇关于使用 TypeScript 在 Vue.js 3 中输入的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 01:47:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1146378.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:道具   TypeScript   Vue   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!