我想在 Nuxt v3 中实现一个轮播组件。该组件接收一系列项目。该组件仅实现逻辑,而不实现样式或结构。
现在这是我的组件:
组件/tdx/carousel.vue
<template>
<div>
<slot name="last"></slot>
<div v-for="item in items">
<slot
name="item"
v-bind="item"
></slot>
</div>
<slot name="next"></slot>
</div>
</template>
<script setup lang="ts">
const props = defineProps({
items: {
type: [],
required: true,
},
spotlight: {
type: Number,
default: 1,
validator(value: number) {
return value > 0;
},
},
});
</script>
这里轮播的逻辑并不重要。
在父组件中,我可以像这样使用该组件:
<template>
<div class="container">
<TdxCarousel :items="exampleArray">
<template #item="{ title, description }">
<p class="font-semibold text-2xl">{{ title }}</p>
<hr />
<p>{{ description }}</p>
</template>
</TdxCarousel>
</div>
</template>
<script setup lang="ts">
const exampleArray = ref([
{
title: 'Item 1',
description: 'Desc of item 1',
},
{
title: 'Item 2',
description: 'Desc of item 2',
},
]);
</script>
这很好用。除此之外我想要的是打字。 title 和 description 的类型当然是any,因为在 carousel.vue 的 props 中,项目的类型是 unknown[]。
我发现这篇文章展示了如何制作通用组件,但我不想要这个,因为我不得不弄乱 nuxt 的自动导入系统。
如何从 carousel.vue 属性中的给定项目实现类型推断?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
更新:2023 年 5 月
从 Vue 3.3 开始,正式支持通用组件.
您需要定义一个通用参数。修改
carousel.vue组件以使用标记中的generic属性,并将其转换为使用基于类型的defineProps的方法,以便它正确地获取泛型。<script setup lang="ts" generic="T extends any"> withDefaults( defineProps<{ items: T[]; spotlight?: number }>(), { spotlight: 1, }); </script> <template> <div> <slot name="last"></slot> <div v-for="item in items"> <slot name="item" v-bind="item"> </slot> </div> <slot name="next"></slot> </div> </template>现在,插槽上的道具将根据物品类型正确推断。
2023 年 5 月之前
在 VSCode/Volar 的早期版本中,您需要启用实验性标志 。 它需要在
vueCompilerOptions下启用 tsconfig.json 的experimentalRfc436选项。// tsconfig.json { // ... "vueCompilerOptions": { "experimentalRfc436": true } }这不再是必要的,因为它在最新版本的 Volar 中默认启用。