---
title: "ScrollArea"
description: "Гибкая прокручиваемая область с виртуализацией для работы с большими наборами данных при высокой производительности."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/scroll-area"
---
# ScrollArea

> Гибкая прокручиваемая область с виртуализацией для работы с большими наборами данных при высокой производительности.

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

ScrollArea создаёт прокручиваемые контейнеры с необязательной виртуализацией для больших списков.

```vue [ScrollAreaExample.vue]
<script setup lang="ts">
const heights = [320, 480, 640, 800]

// Псевдослучайный выбор высоты с длинным циклом, чтобы не было повторяющихся узоров
function getHeight(index: number) {
  const seed = (index * 11 + 7) % 17
  return heights[seed % heights.length]!
}

const items = Array.from({ length: 1000 }).map((_, index) => {
  const height = getHeight(index)

  return {
    id: index,
    title: `Элемент ${index + 1}`,
    src: `https://placehold.co/640x${height}?text=${index}`,
    width: 640,
    height
  }
})
</script>

<template>
  <B24ScrollArea
    v-slot="{ item, index }"
    :items="items"
    orientation="vertical"
    :virtualize="{
      gap: 16,
      lanes: 3,
      estimateSize: 480
    }"
    class="w-full h-128 p-4 scrollbar-thin"
  >
    <img
      :src="item.src"
      :alt="item.title"
      :width="item.width"
      :height="item.height"
      :loading="index > 8 ? 'lazy' : 'eager'"
      class="rounded-md size-full object-cover"
    >
  </B24ScrollArea>
</template>
```

### Элементы

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

```vue [ScrollAreaItemsExample.vue]
<script setup lang="ts">
const items = Array.from({ length: 30 }, (_, i) => ({
  id: i + 1,
  title: `Элемент ${i + 1}`,
  description: `Описание элемента ${i + 1}`
}))
</script>

<template>
  <B24ScrollArea
    v-slot="{ item, index }"
    :items="items"
    class="w-full h-96 scrollbar-thin"
  >
    <B24PageCard
      v-bind="item"
      :variant="index % 2 === 0 ? 'filled' : 'outline'"
      class="rounded-none"
    />
  </B24ScrollArea>
</template>
```

> [!TIP]
> See: #with-default-slot
> Слот по умолчанию можно использовать и без пропса `items`, чтобы напрямую отрисовать произвольное прокручиваемое содержимое.

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

Пропс `orientation` меняет направление прокрутки. По умолчанию `vertical`.

```vue [ScrollAreaOrientationExample.vue]
<script setup lang="ts">
defineProps<{
  orientation?: 'vertical' | 'horizontal'
}>()

const items = Array.from({ length: 30 }, (_, i) => ({
  id: i + 1,
  title: `Элемент ${i + 1}`,
  description: `Описание элемента ${i + 1}`
}))
</script>

<template>
  <B24ScrollArea
    v-slot="{ item, index }"
    :items="items"
    :orientation="orientation"
    class="w-full data-[orientation=vertical]:h-96 scrollbar-thin"
  >
    <B24PageCard
      v-bind="item"
      :variant="index % 2 === 0 ? 'filled' : 'outline'"
      class="rounded-none"
    />
  </B24ScrollArea>
</template>
```

### Виртуализация

Пропс `virtualize` отрисовывает только те элементы, которые сейчас на экране, и заметно ускоряет работу с большими наборами данных.

> [!NOTE]
> При **включённой** виртуализации отступы настраиваются опциями пропса `virtualize`: `gap`, `paddingStart` и `paddingEnd`. Без виртуализации применяйте пропс `b24ui`, например классы `gap p-4` для слота `viewport`.

> [!TIP]
> Если у всех элементов **одинаковая высота**, задайте в пропсе `virtualize` значение `skipMeasurement: true`: компонент перестанет измерять каждый элемент в DOM и будет опираться на `estimateSize`. Это заметно ускоряет большие однородные списки.

```vue [ScrollAreaVirtualizeExample.vue]
<script setup lang="ts">
defineProps<{
  orientation?: 'vertical' | 'horizontal'
}>()

const items = computed(() => Array.from({ length: 1000 }, (_, i) => ({
  id: i + 1,
  title: `Элемент ${i + 1}`,
  description: `Описание элемента ${i + 1}`
})))
</script>

<template>
  <B24ScrollArea
    v-slot="{ item, index }"
    :items="items"
    :orientation="orientation"
    virtualize
    class="w-full data-[orientation=vertical]:h-96 data-[orientation=horizontal]:h-24.5  scrollbar-thin"
  >
    <B24PageCard
      v-bind="item"
      :variant="index % 2 === 0 ? 'filled' : 'outline'"
      class="rounded-none"
    />
  </B24ScrollArea>
</template>
```

### Тень прокрутки

Пропс `shadow` показывает затухающую тень на краях прокрутки и подсказывает, что в этом направлении есть ещё содержимое. Тень следует за `orientation` и появляется, только когда содержимое не помещается.

```vue [ScrollAreaShadowExample.vue]
<template>
  <div class="max-w-sm bg-elevated/50 rounded-lg">
    <B24ScrollArea
      shadow
      class="p-4 h-72"
      :b24ui="{ viewport: 'gap-4' }"
    >
      <p v-for="i in 6" :key="i">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pulvinar risus non risus hendrerit venenatis. Pellentesque sit amet hendrerit risus, sed porttitor quam. Morbi accumsan cursus enim, sed ultricies sapien.
      </p>
    </B24ScrollArea>
  </div>
</template>
```

> [!TIP]
> Объект в пропсе `shadow` настраивает размер затухания, например `:shadow="{ size: 48 }"`.

## Примеры

### Раскладка masonry

Пропс `virtualize` с опциями `lanes`, `gap` и `estimateSize` строит раскладки masonry в стиле Pinterest с элементами разной высоты.

```vue [ScrollAreaMasonryLayoutExample.vue]
<script setup lang="ts">
withDefaults(defineProps<{
  orientation?: 'vertical' | 'horizontal'
  lanes?: number
  gap?: number
}>(), {
  orientation: 'vertical',
  lanes: 3,
  gap: 16
})

const heights = [320, 480, 640, 800]

function getHeight(index: number) {
  const seed = (index * 11 + 7) % 17
  return heights[seed % heights.length]!
}

const items = Array.from({ length: 1000 }).map((_, index) => {
  const height = getHeight(index)

  return {
    id: index,
    title: `Элемент ${index + 1}`,
    src: `https://placehold.co/640x${height}?text=${index}`,
    width: 640,
    height
  }
})
</script>

<template>
  <B24ScrollArea
    v-slot="{ item }"
    :items="items"
    :orientation="orientation"
    :virtualize="{
      gap,
      lanes,
      estimateSize: 480
    }"
    class="w-full h-128 p-4 scrollbar-thin"
  >
    <img
      :src="item.src"
      :alt="item.title"
      :width="item.width"
      :height="item.height"
      loading="lazy"
      class="rounded-md size-full object-cover"
    >
  </B24ScrollArea>
</template>
```

> [!TIP]
> Для лучшей производительности задайте `estimateSize` близким к средней высоте элемента. Больший `overscan` делает прокрутку плавнее, но отрисовывает больше элементов за пределами экрана.

### С адаптивным числом колонок

Чтобы сделать `lanes` реактивным, используйте композаблы [`useWindowSize`](https://vueuse.org/core/useWindowSize/) (по области просмотра) или [`useElementSize`](https://vueuse.org/core/useElementSize/) (по контейнеру).

```vue [ScrollAreaResponsiveLanesExample.vue]
<script setup lang="ts">
import { useElementSize } from '@vueuse/core'

const items = Array.from({ length: 1000 }).map((_, index) => ({
  id: index,
  title: `Элемент ${index + 1}`,
  src: `https://placehold.co/640x480?text=${index}`,
  width: 640,
  height: 480
}))

const gap = 16
const scrollArea = useTemplateRef('scrollArea')
const { width } = useElementSize(() => scrollArea.value?.$el)

const lanes = computed(() => Math.max(1, Math.min(4, Math.floor(width.value / 200))))
const laneWidth = computed(() => (width.value - (lanes.value - 1) * gap) / lanes.value)
const estimateSize = computed(() => laneWidth.value * (480 / 640))
</script>

<template>
  <B24ScrollArea
    ref="scrollArea"
    v-slot="{ item }"
    :items="items"
    :virtualize="{
      gap,
      lanes,
      estimateSize,
      skipMeasurement: true
    }"
    class="w-full h-96 p-4 scrollbar-thin"
  >
    <img
      :src="item.src"
      :alt="item.title"
      :width="item.width"
      :height="item.height"
      loading="lazy"
      class="rounded-md size-full object-cover"
    >
  </B24ScrollArea>
</template>
```

### С внешним элементом прокрутки `New`

Передайте в пропс `virtualize` функцию `getScrollElement`, чтобы виртуализировать относительно прокручиваемого предка, а не собственной области компонента. `scrollMargin` задаёт смещение списка от начала элемента прокрутки (например, высоту содержимого над ним).

```vue [ScrollAreaExternalScrollExample.vue]
<script setup lang="ts">
import { useElementSize } from '@vueuse/core'
import ArrowToTheTopIcon from '@bitrix24/b24icons-vue/actions/ArrowToTheTopIcon'
import ArrowToTheLeftIcon from '@bitrix24/b24icons-vue/actions/ArrowToTheLeftIcon'

const props = withDefaults(defineProps<{
  orientation?: 'vertical' | 'horizontal'
}>(), {
  orientation: 'vertical'
})

type User = {
  id: number
  firstName: string
  lastName: string
  email: string
  image: string
}

const { data: users } = useLazyFetch('https://dummyjson.com/users?limit=100&select=firstName,lastName,email,image', {
  key: 'scroll-area-external-scroll-users',
  transform: (data?: { users: User[] }) => data?.users ?? [],
  default: () => [] as User[],
  server: false
})

const isHorizontal = computed(() => props.orientation === 'horizontal')

// Прокруткой управляет контейнер; список виртуализируется относительно него, поэтому у шапки и карточек одна полоса прокрутки.
const container = useTemplateRef('container')
const title = useTemplateRef('title')

// Размер элемента вдоль оси прокрутки: ширина карточки при горизонтальной прокрутке, высота строки — при вертикальной.
const itemSize = computed(() => isHorizontal.value ? 256 : 88)
const getScrollElement = () => container.value

// `scrollMargin` — смещение заголовка вдоль оси прокрутки: его ширина, если он слева от карточек, и высота, если над ними.
const { width: titleWidth, height: titleHeight } = useElementSize(title, undefined, { box: 'border-box' })
const scrollMargin = computed(() => isHorizontal.value ? titleWidth.value : titleHeight.value)

function scrollToStart() {
  container.value?.scrollTo(isHorizontal.value ? { left: 0, behavior: 'smooth' } : { top: 0, behavior: 'smooth' })
}
</script>

<template>
  <div
    ref="container"
    :class="isHorizontal ? 'w-full overflow-x-auto scrollbar-thin' : 'w-full h-128 overflow-y-auto scrollbar-thin'"
  >
    <div :class="isHorizontal && 'flex'">
      <div
        ref="title"
        class="z-10 flex gap-4 bg-elevated/50 backdrop-blur-sm"
        :class="isHorizontal
          ? 'sticky start-0 w-72 shrink-0 flex-col justify-center p-6 border-e border-muted'
          : 'sticky top-0 items-end justify-between px-6 py-4 border-b border-muted'"
      >
        <div>
          <h2 class="text-2xl font-bold">
            Участники
          </h2>
          <p class="text-muted">
            Эта шапка прокручивается вместе с карточками, у них одна полоса прокрутки.
          </p>
        </div>
        <B24Button
          :icon="isHorizontal ? ArrowToTheLeftIcon : ArrowToTheTopIcon"
          color="air-tertiary"
          :class="isHorizontal && 'self-start'"
          :label="isHorizontal ? 'Начало' : 'Верх'"
          @click="scrollToStart"
        />
      </div>

      <B24ScrollArea
        v-slot="{ item }"
        :orientation="orientation"
        :items="users"
        :class="isHorizontal && 'h-48 shrink-0'"
        :virtualize="{ scrollMargin, getScrollElement, estimateSize: itemSize, skipMeasurement: isHorizontal }"
      >
        <B24PageCard
          orientation="horizontal"
          class="rounded-none h-full"
          :class="isHorizontal && 'w-64'"
        >
          <B24User
            :name="`${item.firstName} ${item.lastName}`"
            :description="item.email"
            :avatar="{ src: item.image, alt: item.firstName, loading: 'lazy' as const }"
            size="lg"
          />
        </B24PageCard>
      </B24ScrollArea>
    </div>
  </div>
</template>
```

> [!NOTE]
> Контейнер сам управляет прокруткой, поэтому кнопка «Top»/«Start» в шапке прокручивает его напрямую через `container.scrollTo`.

> [!CAUTION]
> В этом режиме пропс `shadow` не действует, потому что корневой элемент больше не управляет прокруткой. Добавьте затухание на прокручиваемый контейнер самостоятельно.

### С программной прокруткой

Через доступный `virtualizer` положением прокрутки можно управлять программно.

```vue [ScrollAreaScrollToExample.vue]
<script setup lang="ts">
const items = computed(() => Array.from({ length: 1000 }, (_, i) => ({
  id: i + 1,
  title: `Элемент ${i + 1}`
})))

const scrollArea = useTemplateRef('scrollArea')

const targetIndex = ref(500)

function scrollToTop() {
  scrollArea.value?.virtualizer?.scrollToIndex(0, { align: 'start', behavior: 'smooth' })
}

function scrollToBottom() {
  scrollArea.value?.virtualizer?.scrollToIndex(items.value.length - 1, { align: 'end', behavior: 'smooth' })
}

function scrollToItem(index: number) {
  scrollArea.value?.virtualizer?.scrollToIndex(index - 1, { align: 'center', behavior: 'smooth' })
}
</script>

<template>
  <div class="w-full">
    <B24ScrollArea
      v-slot="{ item, index }"
      ref="scrollArea"
      :items="items"
      :virtualize="{
        estimateSize: 72,
        skipMeasurement: true
      }"
      class="h-96 w-full scrollbar-thin"
    >
      <B24PageCard
        v-bind="item"
        :variant="index % 2 === 0 ? 'filled' : 'outline'"
        class="rounded-none isolate"
        :class="[index === (targetIndex - 1) && 'bg-(--ui-color-accent-main-primary-alt-2)']"
      />
    </B24ScrollArea>

    <B24FieldGroup size="sm" class="px-4 py-3 border-t border-muted w-full">
      <B24Button
        label="Сверху"
        @click="scrollToTop"
      />
      <B24Button
        label="Снизу"
        @click="scrollToBottom"
      />
      <B24Button
        :label="`Перейти к ${targetIndex || 500}`"
        @click="scrollToItem(targetIndex || 500)"
      />
    </B24FieldGroup>
  </div>
</template>
```

### С бесконечной прокруткой

Композабл [`useInfiniteScroll`](https://vueuse.org/core/useInfiniteScroll/) подгружает данные по мере прокрутки.

```vue [ScrollAreaInfiniteScrollExample.vue]
<script setup lang="ts">
import { useInfiniteScroll } from '@vueuse/core'
import { sleepAction } from '~/utils/sleep'

type User = {
  id: number
  firstName: string
  lastName: string
  username: string
  email: string
  image: string
}

type UserResponse = {
  users: User[]
  total: number
  skip: number
  limit: number
}

const skip = ref(0)

const { data, status } = useLazyFetch('https://dummyjson.com/users?limit=10&select=firstName,lastName,username,email,image', {
  key: 'scroll-area-users-infinite-scroll',
  query: { skip },
  transform: async (data?: UserResponse) => {
    // Имитируем задержку
    await sleepAction(1000)
    return data?.users
  },
  server: false
})

const users = ref<User[]>([])

watch(data, () => {
  users.value = [
    ...users.value,
    ...(data.value || [])
  ]
})

const scrollArea = useTemplateRef('scrollArea')

onMounted(() => {
  useInfiniteScroll(scrollArea.value?.$el, () => {
    skip.value += 10
  }, {
    distance: 200,
    canLoadMore: () => {
      return status.value !== 'pending'
    }
  })
})
</script>

<template>
  <B24ScrollArea
    ref="scrollArea"
    v-slot="{ item }"
    :items="users"
    :virtualize="{
      estimateSize: 88,
      skipMeasurement: true
    }"
    class="relative h-96 w-full scrollbar-thin"
  >
    <B24PageCard
      orientation="horizontal"
      class="rounded-none"
    >
      <B24User
        :name="`${item.firstName} ${item.lastName}`"
        :description="item.email"
        :avatar="{ src: item.image, alt: item.firstName, loading: 'lazy' }"
        size="lg"
      />
    </B24PageCard>
  </B24ScrollArea>

  <B24Progress
    v-show="status === 'pending' || status === 'idle'"
    animation="elastic"
    indeterminate
    size="xs"
    class="absolute top-0 inset-x-0 z-1"
    :b24ui="{ base: 'bg-default' }"
  />
</template>
```

> [!NOTE]
> В примере `useLazyFetch` с `server: false` загружает данные на клиенте, не блокируя первую отрисовку. Состояние загрузки проверяет и `pending`, и `idle`, чтобы индикатор показывался и до запроса, и во время него. Новые страницы подгружаются по мере прокрутки.

### Со слотом по умолчанию

Слот по умолчанию можно использовать без пропса `items`, чтобы напрямую отрисовать произвольное прокручиваемое содержимое.

```vue [ScrollAreaDefaultSlotExample.vue]
<template>
  <B24ScrollArea class="h-96 w-full scrollbar-thin" :b24ui="{ viewport: 'gap-4 p-4' }">
    <B24PageCard title="Раздел 1" description="Произвольное содержимое без пропса items." />
    <B24PageCard title="Раздел 2" description="Произвольное содержимое без пропса items." />
    <B24PageCard title="Раздел 3" description="Произвольное содержимое без пропса items." />
    <B24PageCard title="Раздел 4" description="Произвольное содержимое без пропса items." />
    <B24PageCard title="Раздел 5" description="Произвольное содержимое без пропса items." />
    <B24PageCard title="Раздел 6" description="Произвольное содержимое без пропса items." />
  </B24ScrollArea>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the ScrollArea component
 */
interface ScrollAreaProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  /**
   * The scroll direction.
   * @default 'vertical'
   */
  orientation?: "vertical" | "horizontal" | undefined;
  /**
   * Array of items to render.
   */
  items?: T[] | undefined;
  /**
   * Enable virtualization for large lists.
   * @default false
   */
  virtualize?: boolean | ScrollAreaVirtualizeOptions | undefined;
  /**
   * Display fade shadows on the scrollable edges to indicate more content.
   * Pass an object to configure the shadow size (in px).
   * @default false
   */
  shadow?: boolean | { size?: number | undefined; } | undefined;
  b24ui?: { root?: SlotClass; viewport?: SlotClass; item?: SlotClass; } | undefined;
}
```

### Слоты

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

### События

```ts
/**
 * Emitted events for the ScrollArea component
 */
interface ScrollAreaEmits {
  scroll: (payload: [isScrolling: boolean]) => void;
}
```

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

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

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

// Прокрутить к нужному элементу
function scrollToItem(index: number) {
  scrollArea.value?.virtualizer?.scrollToIndex(index, { align: 'center' })
}
</script>

<template>
  <B24ScrollArea ref="scrollArea" :items="items" virtualize />
</template>
```

Он даёт доступ к следующему:

| Имя | Тип | Описание |
| --- | --- | --- |
| `$el` | `HTMLElement` | Корневой элемент компонента. |
| `virtualizer` | `Ref<Virtualizer> \| undefined` | Экземпляр виртуализатора [TanStack Virtual](https://tanstack.com/virtual/v3/docs/api/virtualizer) (`undefined`, если виртуализация отключена). |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    scrollArea: {
      slots: {
        root: 'relative',
        viewport: 'relative flex',
        item: ''
      },
      variants: {
        orientation: {
          vertical: {
            root: 'overflow-y-auto overflow-x-hidden',
            viewport: 'flex-col',
            item: ''
          },
          horizontal: {
            root: 'overflow-x-auto overflow-y-hidden',
            viewport: 'flex-row',
            item: ''
          }
        },
        externalScroll: {
          true: {
            root: 'overflow-visible'
          }
        }
      }
    }
  }
})
```

## Sitemap

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