Перейти к содержанию

Carousel

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

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

Компонент 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>
  <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>
На компьютере карусель можно тянуть мышью по горизонтали.

Элементы

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

<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 / 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>
  <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.

На компьютере вертикальную карусель можно тянуть мышью сверху вниз.
<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>
В вертикальной ориентации контейнеру нужна высота.

Стрелки

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

<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. По умолчанию кнопки air-secondary-no-accent.

<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 из набора иконок интерфейса; при письме справа налево они меняются местами.

<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 выводит точки, по которым можно перейти к нужному слайду.

<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>

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

<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. Плагин загружается, только когда включён его пропс.

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

Пропс autoplay — true или объект настроек плагина 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>
  <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>
В примере включён loop — карусель бесконечная.

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

Пропс auto-scroll — true или объект настроек плагина 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>
  <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>
В примере включён loop — карусель бесконечная.

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

Пропс auto-height — true или объект настроек плагина 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>
  <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>
Класс transition-[height] у контейнера делает смену высоты плавной.

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

Пропс class-names — true или объект настроек плагина Class Names — ставит слайдам классы состояния (is-snapped и другие).

<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>
Классы transition-opacity [&:not(.is-snapped)]:opacity-10 у item плавно гасят слайды вне центра.

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

Пропс fade — true или объект настроек плагина 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>
  <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 — листает карусель колесом мыши или тачпадом.

Прокрутите карусель колесом мыши.
<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 у emblaApi переходит к слайду по нажатию на миниатюру под каруселью.

<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>
<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'

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

Пропсы

Пропс По умолчанию Тип
as'div'any

The element or component this component should render as.

prev{ color: 'air-secondary-no-accent' } Omit<ButtonProps, LinkPropsKeys>

Configure the prev button when arrows are enabled.

prevIconicons.arrowLeft IconProp

The icon displayed in the prev button.

next{ color: 'air-secondary-no-accent' } Omit<ButtonProps, LinkPropsKeys>

Configure the next button when arrows are enabled.

nextIconicons.arrowRight IconProp

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">; }
b24ui { root?: SlotClass; viewport?: SlotClass; container?: SlotClass; item?: SlotClass; controls?: SlotClass; arrows?: SlotClass; prev?: SlotClass; next?: SlotClass; dots?: SlotClass; dot?: SlotClass; }

Слоты

Слот Тип
default{ item: T; index: number; }

События

Событие Тип
select[selectedIndex: number]

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

Типизированный экземпляр компонента доступен через useTemplateRef.

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

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

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

ИмяТип
emblaRefRef<HTMLElement | null>
emblaApiRef<EmblaCarouselType | null>

Тема

Была ли страница полезна?