Carousel

EmblaGitLab
Um carrossel com movimento e gestos de deslize construído com o Embla.

Uso

Use o componente Carousel para exibir uma lista de itens em um carrossel.

Use o mouse para arrastar o carrossel horizontalmente no desktop.

Itens

Use a prop items como um array e renderize cada item usando o slot padrão:

Você também pode passar um array de objetos com as seguintes propriedades:

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

Você pode controlar quantos itens ficam visíveis usando as classes utilitárias basis / width no item:

Orientação

Use a prop orientation para alterar a orientação do Progress. O padrão é horizontal.

Use o mouse para arrastar o carrossel verticalmente no desktop.
Você precisa especificar um height no container na orientação vertical.

Setas

Use a prop arrows para exibir os botões de anterior e próximo.

Anterior / Próximo

Use as props prev e next para personalizar os botões de anterior e próximo com quaisquer props do Button.

Ícones de anterior / próximo

Use as props prev-icon e next-icon para personalizar o Icon dos botões. O padrão é i-lucide-arrow-left / i-lucide-arrow-right.

Você pode personalizar esses ícones globalmente no seu app.config.ts nas chaves ui.icons.arrowLeft / ui.icons.arrowRight.
Você pode personalizar esses ícones globalmente no seu vite.config.ts nas chaves ui.icons.arrowLeft / ui.icons.arrowRight.

Pontos

Use a prop dots para exibir uma lista de pontos para rolar até um slide específico.

O número de pontos é baseado no número de slides exibidos na visualização:

Plugins

O componente Carousel implementa os plugins oficiais do Embla Carousel.

Reprodução automática

Este plugin é usado para estender o Embla Carousel com a funcionalidade de reprodução automática.

Use a prop autoplay como um booleano ou um objeto para configurar o plugin Autoplay.

Neste exemplo, usamos a prop loop para um carrossel infinito.

Rolagem automática

Este plugin é usado para estender o Embla Carousel com a funcionalidade de rolagem automática.

Use a prop auto-scroll como um booleano ou um objeto para configurar o plugin Auto Scroll.

Neste exemplo, usamos a prop loop para um carrossel infinito.

Altura automática

Este plugin é usado para estender o Embla Carousel com a funcionalidade de altura automática. Ele altera a altura do container do carrossel para se ajustar à altura do slide mais alto em exibição.

Use a prop auto-height como um booleano ou um objeto para configurar o plugin Auto Height.

Neste exemplo, adicionamos a classe transition-[height] no container para animar a mudança de altura.

Nomes de classe

O Class Names é um plugin utilitário de alternância de nomes de classe para o Embla Carousel que permite automatizar a alternância de nomes de classe no seu carrossel.

Use a prop class-names como um booleano ou um objeto para configurar o plugin Class Names.

Neste exemplo, adicionamos as classes transition-opacity [&:not(.is-snapped)]:opacity-10 no item para animar a mudança de opacidade.

Fade

Este plugin é usado para substituir a funcionalidade de rolagem do Embla Carousel por transições de fade.

Use a prop fade como um booleano ou um objeto para configurar o plugin Fade.

Gestos de roda do mouse

Este plugin é usado para estender o Embla Carousel com a capacidade de usar a roda do mouse/trackpad para navegar pelo carrossel.

Use a prop wheel-gestures como um booleano ou um objeto para configurar o plugin Wheel Gestures.

Use a roda do mouse para rolar o carrossel.

Exemplos

Com miniaturas

Você pode usar a função scrollTo da emblaApi para exibir miniaturas sob o carrossel que permitem navegar até um slide específico.

API

Props

Prop Default Type
as'div'any

The element or component this component should render as.

prev{ size: 'md', color: 'neutral', variant: 'link' } Omit<ButtonProps, LinkPropsKeys>

Configure the prev button when arrows are enabled.

prevIconappConfig.ui.icons.arrowLeftany

The icon displayed in the prev button.

next{ size: 'md', color: 'neutral', variant: 'link' } Omit<ButtonProps, LinkPropsKeys>

Configure the next button when arrows are enabled.

nextIconappConfig.ui.icons.arrowRightany

The icon displayed in the next button.

arrowsfalseboolean

Display prev and next buttons to scroll the carousel.

dotsfalseboolean

Display dots to scroll to a specific slide.

orientation'horizontal' "vertical" | "horizontal"

The orientation of the carousel.

items T[]
autoplayfalseboolean | Partial<CreateOptionsType<OptionsType>>

Enable Autoplay plugin

autoScrollfalseboolean | Partial<CreateOptionsType<OptionsType>>

Enable Auto Scroll plugin

autoHeightfalseboolean | Partial<CreateOptionsType<{ active: boolean; breakpoints: { [key: string]: Omit<Partial<any>, "breakpoints">; }; }>>

Enable Auto Height plugin

classNamesfalseboolean | Partial<CreateOptionsType<OptionsType>>

Enable Class Names plugin

fadefalseboolean | Partial<CreateOptionsType<{ active: boolean; breakpoints: { [key: string]: Omit<Partial<any>, "breakpoints">; }; }>>

Enable Fade plugin

wheelGesturesfalseboolean | WheelGesturesPluginOptions

Enable Wheel Gestures plugin

align'center' "start" | "center" | "end" | (viewSize: number, snapSize: number, index: number): number
containScroll'trimSnaps' false | "trimSnaps" | "keepSnaps"
slidesToScroll1 number | "auto"
dragFreefalseboolean
dragThreshold10 number
inViewThreshold0 number | number[]
loopfalseboolean
skipSnapsfalseboolean
duration25 number
startIndex0 number
watchDragtrue false | true | (emblaApi: EmblaCarouselType, evt: PointerEventType): boolean | void
watchResizetrue false | true | (emblaApi: EmblaCarouselType, entries: ResizeObserverEntry[]): boolean | void
watchSlidestrue false | true | (emblaApi: EmblaCarouselType, mutations: MutationRecord[]): boolean | void
watchFocustrue false | true | (emblaApi: EmblaCarouselType, evt: FocusEvent): boolean | void
activetrueboolean
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">; }
ui { root?: SlotClass; viewport?: SlotClass; container?: SlotClass; item?: SlotClass; controls?: SlotClass; arrows?: SlotClass; prev?: SlotClass; next?: SlotClass; dots?: SlotClass; dot?: SlotClass; }

Slots

Slot Type
default{ item: T; index: number; }

Emits

Event Type
select[selectedIndex: number]

Expose

Você pode acessar a instância tipada do componente usando useTemplateRef.

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

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

Isso dará a você acesso ao seguinte:

NameType
emblaRefRef<HTMLElement | null>
emblaApiRef<EmblaCarouselType | null>

Tema

app.config.ts
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 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'
          }
        }
      }
    }
  }
})
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ui from '@nitro/ui/vite'

export default defineConfig({
  plugins: [
    vue(),
    ui({
      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 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'
              }
            }
          }
        }
      }
    })
  ]
})

Changelog

No recent changes