본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Carousel

원문 보기 위키 갱신

Embla로 만든 모션과 스와이프를 지원하는 캐러셀 컴포넌트예요.

출처: Nuxt UI

본문

사용법

Carousel 컴포넌트를 사용해 항목 목록을 캐러셀로 보여 줄 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    loop
    arrows
    :autoplay="{ delay: 2000 }"
    wheel-gestures
    :prev="{ variant: 'solid' }"
    :next="{ variant: 'solid' }"
    :items="items"
    :ui="{
      item: 'basis-1/3 ps-0',
      prev: 'sm:start-8',
      next: 'sm:end-8',
      container: 'ms-0'
    }"
  >
    <img :src="item" width="320" height="320">
  </UCarousel>
</template>

[!NOTE]

데스크톱에서는 마우스로 캐러셀을 가로로 드래그해 보세요.

Items

items prop을 배열로 전달하고 기본 슬롯으로 각 항목을 렌더링할 수 있어요:

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel v-slot="{ item }" :items="items" class="w-full max-w-xs mx-auto">
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

다음 속성을 가진 객체 배열도 전달할 수 있어요:

  • class?: any
  • ui?: { item?: ClassNameValue }

basis / width 유틸리티 클래스를 item에 사용하면 몇 개의 항목을 표시할지 조절할 수 있어요:

<script setup lang="ts">
const items = [
  'https://picsum.photos/468/468?random=1',
  'https://picsum.photos/468/468?random=2',
  'https://picsum.photos/468/468?random=3',
  'https://picsum.photos/468/468?random=4',
  'https://picsum.photos/468/468?random=5',
  'https://picsum.photos/468/468?random=6'
]
</script>

<template>
  <UCarousel v-slot="{ item }" :items="items" :ui="{ item: 'basis-1/3' }">
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

Orientation

orientation prop으로 방향을 바꿀 수 있어요. 기본값은 horizontal이에요.

[!NOTE]

데스크톱에서는 마우스로 캐러셀을 세로로 드래그해 보세요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    orientation="vertical"
    :items="items"
    :ui="{ container: 'h-[336px]' }"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

[!CAUTION]

세로 방향에서는 컨테이너에 height를 지정해야 해요.

Arrows

arrows prop으로 이전/다음 버튼을 표시할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel v-slot="{ item }" arrows :items="items" class="w-full max-w-xs mx-auto">
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

Prev / Next

prev와 next prop으로 이전/다음 버튼을 Button의 어떤 속성이든 사용해 커스터마이즈할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    arrows
    :prev="{ color: 'primary' }"
    :next="{ variant: 'solid' }"
    :items="items"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

Prev / Next Icons

prev-icon과 next-icon prop으로 버튼의 Icon을 커스터마이즈할 수 있어요. 기본값은 i-lucide-arrow-left / i-lucide-arrow-right예요.

<script setup lang="ts">
defineProps<{
  prevIcon?: string
  nextIcon?: string
}>()

const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    arrows
    :prev-icon="prevIcon"
    :next-icon="nextIcon"
    :items="items"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

Nuxt:

[!TIP] 참고: /docs/getting-started/integrations/icons/nuxt#theme

app.config.ts의 ui.icons.arrowLeft / ui.icons.arrowRight 키에서 이 아이콘들을 전역으로 커스터마이즈할 수 있어요.

Vue:

[!TIP] 참고: /docs/getting-started/integrations/icons/vue#theme

vite.config.ts의 ui.icons.arrowLeft / ui.icons.arrowRight 키에서 이 아이콘들을 전역으로 커스터마이즈할 수 있어요.

Dots

dots prop으로 특정 슬라이드로 이동하는 점(dot) 목록을 표시할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel v-slot="{ item }" dots :items="items" class="w-full max-w-xs mx-auto">
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

점의 개수는 뷰에 표시되는 슬라이드 수를 기준으로 정해져요:

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel v-slot="{ item }" dots :items="items" :ui="{ item: 'basis-1/3' }">
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

플러그인

Carousel 컴포넌트는 공식 Embla Carousel 플러그인을 구현해요.

Autoplay

이 플러그인은 Embla Carousel에 자동 재생(autoplay) 기능을 추가해요.

autoplay prop을 불리언이나 객체로 전달해 Autoplay 플러그인을 구성할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/468/468?random=1',
  'https://picsum.photos/468/468?random=2',
  'https://picsum.photos/468/468?random=3',
  'https://picsum.photos/468/468?random=4',
  'https://picsum.photos/468/468?random=5',
  'https://picsum.photos/468/468?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    loop
    arrows
    dots
    :autoplay="{ delay: 2000 }"
    :items="items"
    :ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

[!NOTE]

이 예시에서는 무한 캐러셀을 위해 loop prop을 사용하고 있어요.

Auto Scroll

이 플러그인은 Embla Carousel에 자동 스크롤(auto scroll) 기능을 추가해요.

auto-scroll prop을 불리언이나 객체로 전달해 Auto Scroll 플러그인을 구성할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/468/468?random=1',
  'https://picsum.photos/468/468?random=2',
  'https://picsum.photos/468/468?random=3',
  'https://picsum.photos/468/468?random=4',
  'https://picsum.photos/468/468?random=5',
  'https://picsum.photos/468/468?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    loop
    dots
    arrows
    auto-scroll
    :items="items"
    :ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

[!NOTE]

이 예시에서는 무한 캐러셀을 위해 loop prop을 사용하고 있어요.

Auto Height

이 플러그인은 Embla Carousel에 자동 높이(auto height) 기능을 추가해요. 뷰에서 가장 높은 슬라이드의 높이에 맞춰 캐러셀 컨테이너의 높이를 바꿔요.

auto-height prop을 불리언이나 객체로 전달해 Auto Height 플러그인을 구성할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/320?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/320?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/320?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    auto-height
    arrows
    dots
    :items="items"
    :ui="{
      container: 'transition-[height]',
      controls: 'absolute -top-8 inset-x-12',
      dots: '-top-7',
      dot: 'w-6 h-1'
    }"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

[!NOTE]

이 예시에서는 높이 변화를 애니메이션하기 위해 컨테이너에 transition-[height] 클래스를 추가했어요.

Class Names

Class Names는 Embla Carousel의 클래스 이름 토글 유틸리티 플러그인이에요. 캐러셀에서 클래스 이름을 자동으로 토글할 수 있게 해줘요.

class-names prop을 불리언이나 객체로 전달해 Class Names 플러그인을 구성할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/528/528?random=1',
  'https://picsum.photos/528/528?random=2',
  'https://picsum.photos/528/528?random=3',
  'https://picsum.photos/528/528?random=4',
  'https://picsum.photos/528/528?random=5',
  'https://picsum.photos/528/528?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    class-names
    arrows
    :items="items"
    :ui="{
      item: 'basis-[70%] transition-opacity [&:not(.is-snapped)]:opacity-10'
    }"
    class="mx-auto max-w-sm"
  >
    <img :src="item" width="264" height="264" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

[!NOTE]

이 예시에서는 투명도 변화를 애니메이션하기 위해 item에 transition-opacity [&:not(.is-snapped)]:opacity-10 클래스를 추가했어요.

Fade

이 플러그인은 Embla Carousel의 스크롤 기능을 페이드 전환(fade transitions) 으로 대체해요.

fade prop을 불리언이나 객체로 전달해 Fade 플러그인을 구성할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    fade
    arrows
    dots
    :items="items"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

Wheel Gestures

이 플러그인은 Embla Carousel에 마우스/트랙패드 휠로 캐러셀을 탐색하는 기능을 추가해요.

wheel-gestures prop을 불리언이나 객체로 전달해 Wheel Gestures 플러그인을 구성할 수 있어요.

[!NOTE]

마우스 휠로 캐러셀을 스크롤해 보세요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/468/468?random=1',
  'https://picsum.photos/468/468?random=2',
  'https://picsum.photos/468/468?random=3',
  'https://picsum.photos/468/468?random=4',
  'https://picsum.photos/468/468?random=5',
  'https://picsum.photos/468/468?random=6'
]
</script>

<template>
  <UCarousel
    v-slot="{ item }"
    loop
    wheel-gestures
    :items="items"
    :ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </UCarousel>
</template>

예시

썸네일과 함께 사용하기

emblaApi의 scrollTo 메서드를 사용해 캐러셀 아래에 특정 슬라이드로 이동하는 썸네일을 표시할 수 있어요.

<script setup lang="ts">
const items = [
  'https://picsum.photos/640/640?random=1',
  'https://picsum.photos/640/640?random=2',
  'https://picsum.photos/640/640?random=3',
  'https://picsum.photos/640/640?random=4',
  'https://picsum.photos/640/640?random=5',
  'https://picsum.photos/640/640?random=6'
]

const carousel = useTemplateRef('carousel')
const activeIndex = ref(0)

function onClickPrev() {
  activeIndex.value--
}
function onClickNext() {
  activeIndex.value++
}
function onSelect(index: number) {
  activeIndex.value = index
}

function select(index: number) {
  activeIndex.value = index

  carousel.value?.emblaApi?.scrollTo(index)
}
</script>

<template>
  <div class="flex-1 w-full">
    <UCarousel
      ref="carousel"
      v-slot="{ item }"
      arrows
      :items="items"
      :prev="{ onClick: onClickPrev }"
      :next="{ onClick: onClickNext }"
      class="w-full max-w-xs mx-auto"
      @select="onSelect"
    >
      <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
    </UCarousel>

    <div class="flex gap-1 justify-between pt-4 max-w-xs mx-auto">
      <div
        v-for="(item, index) in items"
        :key="index"
        class="size-11 opacity-25 hover:opacity-100 transition-opacity"
        :class="{ 'opacity-100': activeIndex === index }"
        @click="select(index)"
      >
        <img :src="item" width="44" height="44" class="rounded-lg" loading="lazy">
      </div>
    </div>
  </div>
</template>

API

Props

/**
 * Props for the Carousel component
 */
interface CarouselProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  /**
   * Configure the prev button when arrows are enabled.
   * @default { size: 'md', color: 'neutral', variant: 'link' }
   */
  prev?: Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the prev button.
   * @default appConfig.ui.icons.arrowLeft
   */
  prevIcon?: any;
  /**
   * Configure the next button when arrows are enabled.
   * @default { size: 'md', color: 'neutral', variant: 'link' }
   */
  next?: Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the next button.
   * @default appConfig.ui.icons.arrowRight
   */
  nextIcon?: any;
  /**
   * Display prev and next buttons to scroll the carousel.
   * @default false
   */
  arrows?: boolean | undefined;
  /**
   * Display dots to scroll to a specific slide.
   * @default false
   */
  dots?: boolean | undefined;
  /**
   * The orientation of the carousel.
   * @default 'horizontal'
   */
  orientation?: "vertical" | "horizontal" | undefined;
  items?: T[] | undefined;
  /**
   * Enable Autoplay plugin
   * @default false
   */
  autoplay?: boolean | Partial<CreateOptionsType<OptionsType>> | undefined;
  /**
   * Enable Auto Scroll plugin
   * @default false
   */
  autoScroll?: boolean | Partial<CreateOptionsType<OptionsType>> | undefined;
  /**
   * Enable Auto Height plugin
   * @default false
   */
  autoHeight?: boolean | Partial<CreateOptionsType<{ active: boolean; breakpoints: { [key: string]: Omit<Partial<any>, "breakpoints">; }; }>> | undefined;
  /**
   * Enable Class Names plugin
   * @default false
   */
  classNames?: boolean | Partial<CreateOptionsType<OptionsType>> | undefined;
  /**
   * Enable Fade plugin
   * @default false
   */
  fade?: boolean | Partial<CreateOptionsType<{ active: boolean; breakpoints: { [key: string]: Omit<Partial<any>, "breakpoints">; }; }>> | undefined;
  /**
   * Enable Wheel Gestures plugin
   * @default false
   */
  wheelGestures?: boolean | WheelGesturesPluginOptions | undefined;
  ui?: { root?: SlotClass; viewport?: SlotClass; container?: SlotClass; item?: SlotClass; controls?: SlotClass; arrows?: SlotClass; prev?: SlotClass; next?: SlotClass; dots?: SlotClass; dot?: SlotClass; } | undefined;
  /**
   * @default 'center'
   */
  align?: "start" | "center" | "end" | (viewSize: number, snapSize: number, index: number): number | undefined;
  /**
   * @default 'trimSnaps'
   */
  containScroll?: false | "trimSnaps" | "keepSnaps" | undefined;
  /**
   * @default 1
   */
  slidesToScroll?: number | "auto" | undefined;
  /**
   * @default false
   */
  dragFree?: boolean | undefined;
  /**
   * @default 10
   */
  dragThreshold?: number | undefined;
  /**
   * @default 0
   */
  inViewThreshold?: number | number[] | undefined;
  /**
   * @default false
   */
  loop?: boolean | undefined;
  /**
   * @default false
   */
  skipSnaps?: boolean | undefined;
  /**
   * @default 25
   */
  duration?: number | undefined;
  /**
   * @default 0
   */
  startIndex?: number | undefined;
  /**
   * @default true
   */
  watchDrag?: false | true | (emblaApi: EmblaCarouselType, evt: PointerEventType): boolean | void | undefined;
  /**
   * @default true
   */
  watchResize?: false | true | (emblaApi: EmblaCarouselType, entries: ResizeObserverEntry[]): boolean | void | undefined;
  /**
   * @default true
   */
  watchSlides?: false | true | (emblaApi: EmblaCarouselType, mutations: MutationRecord[]): boolean | void | undefined;
  /**
   * @default true
   */
  watchFocus?: false | true | (emblaApi: EmblaCarouselType, evt: FocusEvent): boolean | void | undefined;
  /**
   * @default true
   */
  active?: boolean | undefined;
  /**
   * @default {}
   */
  breakpoints?: { [key: string]: Omit<Partial<CreateOptionsType<{ align: AlignmentOptionType; axis: AxisOptionType; container: string | HTMLElement | null; slides: string | HTMLElement[] | NodeListOf<HTMLElement> | null; containScroll: ScrollContainOptionType; direction: AxisDirectionOptionType; slidesToScroll: SlidesToScrollOptionType; dragFree: boolean; dragThreshold: number; inViewThreshold: number | number[] | undefined; loop: boolean; skipSnaps: boolean; duration: number; startIndex: number; watchDrag: DragHandlerOptionType; watchResize: ResizeHandlerOptionType; watchSlides: SlidesHandlerOptionType; watchFocus: FocusHandlerOptionType; }>>, "breakpoints">; } | undefined;
}

Slots

/**
 * Slots for the Carousel component
 */
interface CarouselSlots {
  default(): any;
}

Emits

/**
 * Emitted events for the Carousel component
 */
interface CarouselEmits {
  select: (payload: [selectedIndex: number]) => void;
}

Expose

useTemplateRef를 사용해 타입이 지정된 컴포넌트 인스턴스에 접근할 수 있어요.

<script setup lang="ts">
const carousel = useTemplateRef('carousel')
</script>

<template>
  <UCarousel ref="carousel" />
</template>

다음에 접근할 수 있어요:

Name Type
emblaRef Ref<HTMLElement | null>
emblaApi Ref<EmblaCarouselType | null>

테마

export default defineAppConfig({
  ui: {
    carousel: {
      slots: {
        root: 'relative focus:outline-none',
        viewport: 'overflow-hidden',
        container: 'flex items-start',
        item: 'min-w-0 shrink-0 basis-full',
        controls: '',
        arrows: '',
        prev: 'absolute rounded-full',
        next: 'absolute rounded-full',
        dots: 'absolute inset-x-0 -bottom-7 flex flex-wrap items-center justify-center gap-3',
        dot: [
          'cursor-pointer size-3 bg-accented rounded-full outline-inverted/25 focus-visible:outline-3',
          'transition'
        ]
      },
      variants: {
        orientation: {
          vertical: {
            container: 'flex-col -mt-4',
            item: 'pt-4',
            prev: 'top-4 sm:-top-12 left-1/2 -translate-x-1/2 rotate-90 rtl:-rotate-90',
            next: 'bottom-4 sm:-bottom-12 left-1/2 -translate-x-1/2 rotate-90 rtl:-rotate-90'
          },
          horizontal: {
            container: 'flex-row -ms-4',
            item: 'ps-4',
            prev: 'start-4 sm:-start-12 top-1/2 -translate-y-1/2',
            next: 'end-4 sm:-end-12 top-1/2 -translate-y-1/2'
          }
        },
        active: {
          true: {
            dot: 'data-[state=active]:bg-inverted'
          }
        }
      }
    }
  }
})

변경 기록

컴포넌트와 테마의 커밋 기록을 확인해 주세요.


사이트맵

전체 페이지 목록은 사이트맵에서 확인할 수 있어요.

더 알아보기 (Learn more)