搜尋

首頁  >  問答  >  主體

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粉863295057491 天前811

全部回覆(1)我來回復

  • P粉476547076

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

    更新:2023 年 5 月

    從 Vue 3.3 開始,正式支援通用元件.

    您需要定義一個通用參數。修改carousel.vue 元件以使用