---
title: "Carousel"
description: "Карусель с прокруткой, перетаскиванием и смахиванием на основе Embla."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/carousel"
---
# Carousel

> Карусель с прокруткой, перетаскиванием и смахиванием на основе Embla.

## Использование

Компонент Carousel показывает список элементов каруселью.

```vue [CarouselExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    loop
    arrows
    :autoplay="{ delay: 2000 }"
    wheel-gestures
    :prev="{ color: 'air-primary' }"
    :next="{ color: 'air-primary' }"
    :items="items"
    :b24ui="{
      item: 'basis-1/3 ps-0',
      prev: 'sm:start-8',
      next: 'sm:end-8',
      container: 'ms-0'
    }"
  >
    <img :src="item" width="320" height="320">
  </B24Carousel>
</template>
```

> [!NOTE]
> На компьютере карусель можно тянуть мышью по горизонтали.

### Элементы

Пропс `items` — массив; каждый элемент выводит слот по умолчанию:

```vue [CarouselItemsExample.vue]
<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>
  <B24Carousel 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">
  </B24Carousel>
</template>
```

Можно передать и массив объектов с полями:

- `class?: any`
- `b24ui?: { item?: ClassNameValue }`

Сколько элементов видно сразу, задают классы [`basis`](https://tailwindcss.com/docs/flex-basis) / [`width`](https://tailwindcss.com/docs/width) у слота `item`:

```vue [CarouselItemsMultipleExample.vue]
<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>
  <B24Carousel v-slot="{ item }" :items="items" :b24ui="{ item: 'basis-1/3' }">
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

### Ориентация

Пропс `orientation` задаёт направление карусели. По умолчанию `horizontal`.

> [!NOTE]
> На компьютере вертикальную карусель можно тянуть мышью сверху вниз.

```vue [CarouselOrientationExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    orientation="vertical"
    :items="items"
    :b24ui="{ container: 'h-[336px]' }"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

> [!CAUTION]
> В вертикальной ориентации контейнеру нужна высота.

### Стрелки

Пропс `arrows` выводит кнопки «назад» и «вперёд».

```vue [CarouselArrowsExample.vue]
<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>
  <B24Carousel 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">
  </B24Carousel>
</template>
```

### Кнопки «назад» и «вперёд»

Пропсы `prev` и `next` принимают любые пропсы [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md). По умолчанию кнопки `air-secondary-no-accent`.

```vue [CarouselPrevNextExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    arrows
    :prev="{ color: 'air-secondary-accent' }"
    :next="{ color: 'air-primary' }"
    :items="items"
    class="w-full max-w-xs mx-auto"
  >
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

### Значки кнопок

Пропсы `prev-icon` и `next-icon` задают значки кнопок. По умолчанию — `arrowLeft` / `arrowRight` из набора иконок интерфейса; при письме справа налево они меняются местами.

```vue [CarouselPrevNextIconExample.vue]
<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>
  <B24Carousel
    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">
  </B24Carousel>
</template>
```

### Точки

Пропс `dots` выводит точки, по которым можно перейти к нужному слайду.

```vue [CarouselDotsExample.vue]
<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>
  <B24Carousel 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">
  </B24Carousel>
</template>
```

Число точек зависит от того, сколько слайдов видно сразу:

```vue [CarouselDotsMultipleExample.vue]
<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>
  <B24Carousel v-slot="{ item }" dots :items="items" :b24ui="{ item: 'basis-1/3' }">
    <img :src="item" width="320" height="320" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

## Плагины

Carousel подключает официальные [плагины Embla Carousel](https://www.embla-carousel.com/docs/v8/plugins). Плагин загружается, только когда включён его пропс.

### Автопрокрутка по слайдам

Пропс `autoplay` — `true` или объект настроек [плагина Autoplay](https://www.embla-carousel.com/docs/v8/plugins/autoplay) — листает слайды сам.

```vue [CarouselAutoplayExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    loop
    arrows
    dots
    :autoplay="{ delay: 2000 }"
    :items="items"
    :b24ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

> [!NOTE]
> В примере включён `loop` — карусель бесконечная.

### Непрерывная прокрутка

Пропс `auto-scroll` — `true` или объект настроек [плагина Auto Scroll](https://www.embla-carousel.com/docs/v8/plugins/auto-scroll) — прокручивает ленту непрерывно.

```vue [CarouselAutoScrollExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    loop
    dots
    arrows
    auto-scroll
    :items="items"
    :b24ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

> [!NOTE]
> В примере включён `loop` — карусель бесконечная.

### Высота по слайду

Пропс `auto-height` — `true` или объект настроек [плагина Auto Height](https://www.embla-carousel.com/docs/v8/plugins/auto-height) — подгоняет высоту карусели под самый высокий видимый слайд.

```vue [CarouselAutoHeightExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    auto-height
    arrows
    dots
    :items="items"
    :b24ui="{
      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">
  </B24Carousel>
</template>
```

> [!NOTE]
> Класс `transition-[height]` у контейнера делает смену высоты плавной.

### Классы состояния

Пропс `class-names` — `true` или объект настроек [плагина Class Names](https://www.embla-carousel.com/docs/v8/plugins/class-names) — ставит слайдам классы состояния (`is-snapped` и другие).

```vue [CarouselClassNamesExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    class-names
    arrows
    :items="items"
    :b24ui="{
      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">
  </B24Carousel>
</template>
```

> [!NOTE]
> Классы `transition-opacity [&:not(.is-snapped)]:opacity-10` у `item` плавно гасят слайды вне центра.

### Смена затуханием

Пропс `fade` — `true` или объект настроек [плагина Fade](https://www.embla-carousel.com/docs/v8/plugins/fade) — меняет слайды затуханием вместо прокрутки.

```vue [CarouselFadeExample.vue]
<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>
  <B24Carousel
    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">
  </B24Carousel>
</template>
```

### Колесо мыши

Пропс `wheel-gestures` — `true` или объект настроек [плагина Wheel Gestures](https://www.embla-carousel.com/docs/v8/plugins/wheel-gestures) — листает карусель колесом мыши или тачпадом.

> [!NOTE]
> Прокрутите карусель колесом мыши.

```vue [CarouselWheelGesturesExample.vue]
<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>
  <B24Carousel
    v-slot="{ item }"
    loop
    wheel-gestures
    :items="items"
    :b24ui="{ item: 'basis-1/3' }"
  >
    <img :src="item" width="234" height="234" class="rounded-lg" loading="lazy">
  </B24Carousel>
</template>
```

## Примеры

### С миниатюрами

Метод [`scrollTo`](https://www.embla-carousel.com/docs/v8/api/methods#scrollto) у [`emblaApi`](#expose) переходит к слайду по нажатию на миниатюру под каруселью.

```vue [CarouselThumbnailsExample.vue]
<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">
    <B24Carousel
      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">
    </B24Carousel>

    <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

### Пропсы

```ts
/**
 * 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 { color: 'air-secondary-no-accent' }
   */
  prev?: Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the prev button.
   * @default icons.arrowLeft
   */
  prevIcon?: IconProp | undefined;
  /**
   * Configure the next button when arrows are enabled.
   * @default { color: 'air-secondary-no-accent' }
   */
  next?: Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the next button.
   * @default icons.arrowRight
   */
  nextIcon?: IconProp | undefined;
  /**
   * 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;
  b24ui?: { 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;
}
```

### Слоты

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

### События

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

### Доступ через ref

Типизированный экземпляр компонента доступен через [`useTemplateRef`](https://vuejs.org/api/composition-api-helpers.html#usetemplateref).

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

<template>
  <B24Carousel ref="carousel" />
</template>
```

Доступны свойства:

| Имя | Тип |
| --- | --- |
| `emblaRef` | `Ref<HTMLElement \| null>` |
| `emblaApi` | [`Ref<EmblaCarouselType \| null>`](https://www.embla-carousel.com/docs/v8/api/methods#typescript) |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    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 isolate flex flex-wrap items-center justify-center gap-3',
        dot: 'relative cursor-pointer size-3 bg-(--ui-color-divider-vibrant-default) rounded-full after:absolute after:-inset-1.5 after:-z-1 outline-(--ui-color-design-outline-focused-stroke) focus-visible:outline-3 motion-safe: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-(--ui-color-accent-main-primary)'
          }
        }
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
