首页  >  问答  >  正文

Vue 3 / Nuxt 3 作用域槽,具有从 props 推断出的通用数据类型

我想在 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>

这很好用。除此之外我想要的是打字。 titledescription 的类型当然是any,因为在 carousel.vue 的 props 中,项目的类型是 unknown[]

我发现这篇文章展示了如何制作通用组件,但我不想要这个,因为我不得不弄乱 nuxt 的自动导入系统。

如何从 carousel.vue 属性中的给定项目实现类型推断?

P粉863295057P粉863295057351 天前701

全部回复(1)我来回复

  • P粉476547076

    P粉4765470762023-11-03 18:29:13

    更新:2023 年 5 月

    从 Vue 3.3 开始,正式支持通用组件.

    您需要定义一个通用参数。修改 carousel.vue 组件以使用