我有一个 Vue 组件,它接收一个 prop
tabs
。这个道具应该遵循这个模式:
[{
id: string
title: string
color: `#${string}`
},{
id: string
title: string
color: `#${string}`
}]
我正在使用 Laravel + Vite + Vue 2,并且因为 Vite 允许我使用 Typescript,所以我想输入我的
tabs
属性。我知道这对于 JS 类型是可能的,但在这里我希望上面的自定义类型作为此 prop 的类型。我已经进行了一些搜索,但没有找到如何执行此操作,除非我开始使用 Vue 3(这在我的项目的当前状态下不会发生)。那么,有谁知道这是否可能,如果可以,该怎么做?
安装 PropType 库:安装 @vue/runtime-core 包,它提供了像 PropType 这样的实用程序,用于在 Vue 2 中进行类型检查。
npm install @vue/runtime-core
在 Vue 组件文件中,您可以使用 JSDoc 注释和 PropType 实用程序定义 tabs prop 的类型。
// YourComponent.vue
<script setup lang="ts">
import { defineProps } from 'vue';
interface Tab {
id: string;
title: string;
color: string;
}
const props = defineProps<{
tabs: Tab[];
}>();
</script>
使用 props 对象访问具有定义类型的 tabs 属性
<template>
<div>
<div v-for="tab in tabs" :key="tab.id">
<!-- Your tab content here -->
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const { tabs } = props;
</script>