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

新手上路,请多包涵

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

所以,我正在这样做:

 <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 看起来像这样:

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

此界面运行良好,但在这种情况下我收到此错误:

 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 认为这是一个值。

我错过了什么?

原文由 chindit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 383
1 个回答

您应该将它与从 vue 导入的 PropType 一起使用,例如 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 创建您的组件,以获得类型推断。

脚本设置

您可以使用 defineProps 函数以两种方式定义道具,但您应该 脚本设置中声明类型/接口,如下所述:

 <script setup lang="ts">

import { ref,PropType, defineComponent , defineProps} from 'vue';
interface FlashInterface {
    level: string,
    message: string,
    id?: string
}
interface IProps{
   message : FlashInterface
}
const props = defineProps<IProps>()

或者

<script setup lang="ts">
...
interface FlashInterface {
    level: string,
    message: string,
    id?: string
}
const props = defineProps({
        message: {
            type: Object as PropType<FlashInterface>,
            required: true
        }
    })

原文由 Boussadjra Brahim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题