---
title: "Sidebar"
description: "Сворачиваемое боковое меню с несколькими вариантами оформления."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/sidebar"
---
# Sidebar

> Сворачиваемое боковое меню с несколькими вариантами оформления.

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

Sidebar — самостоятельное фиксированное боковое меню, которое сдвигает содержимое страницы. На десктопе оно отрисовывается в потоке и сворачивается, на мобильных открывается в компоненте [Modal](https://b24-ui.bx-shef.by/raw/docs/components/modal.md), [Slideover](https://b24-ui.bx-shef.by/raw/docs/components/slideover.md) или [Drawer](https://b24-ui.bx-shef.by/raw/docs/components/drawer.md).

> [!TIP]
> See: /docs/components/dashboard-sidebar/
> **Sidebar и DashboardSidebar.** Sidebar — простое самостоятельное боковое меню, которое можно поставить куда угодно (панель чата, настройки, навигация). Если нужны изменение размера перетаскиванием, сохранение состояния и интеграция с [DashboardGroup](https://b24-ui.bx-shef.by/raw/docs/components/dashboard-group.md), используйте [DashboardSidebar](https://b24-ui.bx-shef.by/raw/docs/components/dashboard-sidebar.md).

Слоты `header`, `default` и `footer` настраивают содержимое меню. Директива `v-model:open` учитывает область просмотра: на десктопе она управляет состоянием «развёрнуто / свёрнуто», на мобильных — самим меню.

```vue [SidebarExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem, NavigationMenuItem } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import PaymentIcon from '@bitrix24/b24icons-vue/outline/PaymentIcon'
import CirclePlusIcon from '@bitrix24/b24icons-vue/outline/CirclePlusIcon'
import PulseCircleIcon from '@bitrix24/b24icons-vue/main/PulseCircleIcon'
import CollabIcon from '@bitrix24/b24icons-vue/outline/CollabIcon'
import SettingsIcon from '@bitrix24/b24icons-vue/main/SettingsIcon'
import ThreePersonsIcon from '@bitrix24/b24icons-vue/outline/ThreePersonsIcon'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import ContrastIcon from '@bitrix24/b24icons-vue/outline/ContrastIcon'
import SunIcon from '@bitrix24/b24icons-vue/outline/SunIcon'
import MoonIcon from '@bitrix24/b24icons-vue/outline/MoonIcon'
import GitHubIcon from '@bitrix24/b24icons-vue/social/GitHubIcon'
import LogOutIcon from '@bitrix24/b24icons-vue/outline/LogOutIcon'
import CloseChatIcon from '@bitrix24/b24icons-vue/outline/CloseChatIcon'

const open = ref(true)

// Тема примера локальная: общий выбор посетителя (colorMode.preference, localStorage сайта) не пишем.
// На странице примера её ведёт страница (exampleThemeKey), в документации — класс на <html> без хранилища.
const appConfig = useAppConfig()
const pageTheme = inject(exampleThemeKey, null)
const currentTheme = ref<'light' | 'dark'>('light')
onMounted(() => {
  currentTheme.value = document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})
function setTheme(mode: 'light' | 'dark') {
  currentTheme.value = mode
  const cls = mode === 'light' ? (appConfig.colorModeTypeLight as string) : 'dark'
  if (pageTheme) {
    pageTheme.value = cls
    return
  }
  const root = document.documentElement
  root.classList.remove('light', 'edge-light', 'dark', 'edge-dark')
  root.classList.add(cls)
}

const teams = ref([
  {
    label: 'Имя ассистента',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      alt: 'assistant',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Bitrix24',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      alt: 'bitrix24',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Имя сотрудника',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      alt: 'employee',
      loading: 'lazy' as const
    }
  }
])
const selectedTeam = ref(teams.value[0])
const selectedTeamFormatted = computed(() => {
  return open.value
    ? selectedTeam.value
    : {
        avatar: selectedTeam.value!.avatar
      }
})

const teamsItems = computed<DropdownMenuItem[][]>(() => {
  return [
    teams.value.map((team, index) => ({
      ...team,
      kbds: ['meta', String(index + 1)],
      onSelect() {
        selectedTeam.value = team
      }
    })),
    [
      { label: 'Создать команду', icon: CirclePlusIcon }
    ]
  ]
})

function getItems(state: 'collapsed' | 'expanded') {
  return [
    {
      label: 'Входящие',
      icon: MailIcon,
      badge: '4'
    },
    {
      label: 'Задачи',
      icon: CollabIcon
    },
    {
      label: 'Действия',
      icon: PulseCircleIcon
    },
    {
      label: 'Настройки',
      icon: SettingsIcon,
      defaultOpen: true,
      children: state === 'expanded'
        ? [
            {
              label: 'Общие',
              icon: HomeIcon
            },
            {
              label: 'Команда',
              icon: ThreePersonsIcon
            },
            {
              label: 'Оплата',
              icon: PaymentIcon
            }
          ]
        : []
    }
  ] satisfies NavigationMenuItem[]
}

const user = ref({
  name: 'Bitrix24',
  avatar: {
    src: 'https://github.com/bitrix24.png',
    alt: 'bitrix24'
  }
})

const userItems = computed<DropdownMenuItem[][]>(() => (
  [
    [
      {
        label: 'Профиль',
        icon: UserIcon
      },
      {
        label: 'Оплата',
        icon: PaymentIcon
      },
      {
        label: 'Настройки',
        icon: SettingsIcon,
        to: '/templates/'
      }
    ],
    [
      {
        label: 'Внешний вид',
        icon: ContrastIcon,
        children: [
          {
            label: 'Светлая',
            icon: SunIcon,
            type: 'checkbox',
            checked: currentTheme.value === 'light',
            onUpdateChecked(checked: boolean) {
              if (checked) {
                setTheme('light')
              }
            },
            onSelect(e: Event) {
              e.preventDefault()
            }
          },
          {
            label: 'Тёмная',
            icon: MoonIcon,
            type: 'checkbox',
            checked: currentTheme.value === 'dark',
            onUpdateChecked(checked: boolean) {
              if (checked) {
                setTheme('dark')
              }
            },
            onSelect(e: Event) {
              e.preventDefault()
            }
          }
        ]
      }
    ],
    [
      {
        label: 'GitHub',
        icon: GitHubIcon,
        to: 'https://github.com/bitrix24/b24ui',
        target: '_blank'
      },
      {
        label: 'Выйти',
        icon: LogOutIcon
      }
    ]
  ]
))

defineShortcuts(extractShortcuts(teamsItems.value))
</script>

<template>
  <div class="flex flex-1">
    <B24Sidebar
      v-model:open="open"
      collapsible="icon"
      rail
      :b24ui="{
        container: 'h-full',
        inner: 'bg-elevated/25 divide-transparent',
        body: 'py-0'
      }"
    >
      <template #header>
        <B24DropdownMenu
          :items="teamsItems"
          :content="{ align: 'start', collisionPadding: 12 }"
          :b24ui="{ content: 'w-[270px]', viewport: 'w-[270px] max-h-[62vh]' }"
        >
          <B24Button
            v-bind="selectedTeamFormatted"
            :use-dropdown="open"
            color="air-tertiary"
            class="w-full data-[state=open]:bg-(--ui-btn-background-hover) overflow-hidden"
            :b24ui="{ trailingIcon: 'text-dimmed ms-auto', label: 'flex-1' }"
          />
        </B24DropdownMenu>
      </template>

      <template #default="{ state }">
        <B24NavigationMenu
          :key="state"
          :items="getItems(state)"
          orientation="vertical"
          :b24ui="{ link: 'p-1.5 overflow-hidden' }"
        />
      </template>

      <template #footer>
        <B24DropdownMenu
          :items="userItems"
          :content="{ align: 'start', side: 'top', sideOffset: 4, collisionPadding: 12 }"
          :b24ui="{ content: 'w-[200px]', viewport: 'w-[200px] max-h-[62vh]' }"
        >
          <B24Button
            v-bind="user"
            :label="open ? user?.name : undefined"
            :use-dropdown="open"
            color="air-tertiary"
            class="w-full data-[state=open]:bg-(--ui-btn-background-hover) overflow-hidden"
            :b24ui="{ trailingIcon: 'text-dimmed ms-auto', label: 'flex-1' }"
          />
        </B24DropdownMenu>
      </template>
    </B24Sidebar>

    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center px-4 border-b border-default">
        <B24Button
          :icon="CloseChatIcon"
          aria-label="Переключить боковое меню"
          size="md"
          color="air-tertiary"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

### Вариант

Пропс `variant` меняет визуальный стиль меню. По умолчанию `sidebar`.

```vue [SidebarPropsExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem, SidebarProps } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import CloseChatIcon from '@bitrix24/b24icons-vue/outline/CloseChatIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-b24/Bitrix24Icon'
import B24Icon from '@bitrix24/b24icons-vue/main/B24Icon'

// В примере пропсы игнорируем
defineProps<Pick<SidebarProps, 'variant' | 'collapsible' | 'side'>>()

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div
    class="flex flex-1"
    :class="[
      variant === 'inset' && 'bg-(--ui-color-g-plastic-greish-bg) dark:bg-(--ui-color-base-black-fixed)',
      side === 'right' && 'flex-row-reverse'
    ]"
  >
    <B24Sidebar
      v-model:open="open"
      :variant="variant"
      :collapsible="collapsible"
      :side="side"
      :b24ui="{
        container: 'h-full'
      }"
    >
      <template #header>
        <Bitrix24Icon v-if="open" class="w-auto h-5 " />
        <B24Icon v-else class="w-auto h-8 text-[#2fc6f6]" />
      </template>

      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col overflow-hidden lg:peer-data-[variant=floating]:my-4 peer-data-[variant=inset]:m-4 lg:peer-data-[variant=inset]:not-peer-data-[collapsible=offcanvas]:ms-0 peer-data-[variant=inset]:rounded-xl peer-data-[variant=inset]:shadow-sm peer-data-[variant=inset]:ring peer-data-[variant=inset]:ring-default bg-default">
      <div
        class="h-(--b24ui-header-height) shrink-0 flex items-center px-4"
        :class="[
          variant !== 'floating' && 'border-b border-default',
          side === 'right' && 'justify-end'
        ]"
      >
        <B24Button
          :icon="side === 'right' ? OpenChatIcon : CloseChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

### Сворачивание

Пропс `collapsible` меняет способ сворачивания меню. По умолчанию `offcanvas`.

- `offcanvas`: меню полностью уезжает за пределы экрана.
- `icon`: меню сужается до ширины иконки.
- `none`: меню не сворачивается.

```vue [SidebarPropsExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem, SidebarProps } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import CloseChatIcon from '@bitrix24/b24icons-vue/outline/CloseChatIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-b24/Bitrix24Icon'
import B24Icon from '@bitrix24/b24icons-vue/main/B24Icon'

// В примере пропсы игнорируем
defineProps<Pick<SidebarProps, 'variant' | 'collapsible' | 'side'>>()

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div
    class="flex flex-1"
    :class="[
      variant === 'inset' && 'bg-(--ui-color-g-plastic-greish-bg) dark:bg-(--ui-color-base-black-fixed)',
      side === 'right' && 'flex-row-reverse'
    ]"
  >
    <B24Sidebar
      v-model:open="open"
      :variant="variant"
      :collapsible="collapsible"
      :side="side"
      :b24ui="{
        container: 'h-full'
      }"
    >
      <template #header>
        <Bitrix24Icon v-if="open" class="w-auto h-5 " />
        <B24Icon v-else class="w-auto h-8 text-[#2fc6f6]" />
      </template>

      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col overflow-hidden lg:peer-data-[variant=floating]:my-4 peer-data-[variant=inset]:m-4 lg:peer-data-[variant=inset]:not-peer-data-[collapsible=offcanvas]:ms-0 peer-data-[variant=inset]:rounded-xl peer-data-[variant=inset]:shadow-sm peer-data-[variant=inset]:ring peer-data-[variant=inset]:ring-default bg-default">
      <div
        class="h-(--b24ui-header-height) shrink-0 flex items-center px-4"
        :class="[
          variant !== 'floating' && 'border-b border-default',
          side === 'right' && 'justify-end'
        ]"
      >
        <B24Button
          :icon="side === 'right' ? OpenChatIcon : CloseChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

> [!TIP]
> See: #slots
> В пропсах слота доступно `state`: по нему можно менять содержимое свёрнутого меню.

### Сторона

Пропс `side` меняет сторону, с которой стоит меню. По умолчанию `left`.

```vue [SidebarPropsExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem, SidebarProps } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import CloseChatIcon from '@bitrix24/b24icons-vue/outline/CloseChatIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'
import Bitrix24Icon from '@bitrix24/b24icons-vue/common-b24/Bitrix24Icon'
import B24Icon from '@bitrix24/b24icons-vue/main/B24Icon'

// В примере пропсы игнорируем
defineProps<Pick<SidebarProps, 'variant' | 'collapsible' | 'side'>>()

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div
    class="flex flex-1"
    :class="[
      variant === 'inset' && 'bg-(--ui-color-g-plastic-greish-bg) dark:bg-(--ui-color-base-black-fixed)',
      side === 'right' && 'flex-row-reverse'
    ]"
  >
    <B24Sidebar
      v-model:open="open"
      :variant="variant"
      :collapsible="collapsible"
      :side="side"
      :b24ui="{
        container: 'h-full'
      }"
    >
      <template #header>
        <Bitrix24Icon v-if="open" class="w-auto h-5 " />
        <B24Icon v-else class="w-auto h-8 text-[#2fc6f6]" />
      </template>

      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col overflow-hidden lg:peer-data-[variant=floating]:my-4 peer-data-[variant=inset]:m-4 lg:peer-data-[variant=inset]:not-peer-data-[collapsible=offcanvas]:ms-0 peer-data-[variant=inset]:rounded-xl peer-data-[variant=inset]:shadow-sm peer-data-[variant=inset]:ring peer-data-[variant=inset]:ring-default bg-default">
      <div
        class="h-(--b24ui-header-height) shrink-0 flex items-center px-4"
        :class="[
          variant !== 'floating' && 'border-b border-default',
          side === 'right' && 'justify-end'
        ]"
      >
        <B24Button
          :icon="side === 'right' ? OpenChatIcon : CloseChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

### Заголовок

Пропс `title` задаёт заголовок шапки меню.

```vue
<template>
  <B24Sidebar title="Навигация">
<Placeholder class="h-full" />
</B24Sidebar>
</template>
```

### Описание

Пропс `description` задаёт описание в шапке меню.

```vue
<template>
  <B24Sidebar title="Навигация" description="Просмотр рабочего пространства">
<Placeholder class="h-full" />
</B24Sidebar>
</template>
```

### Рейка

Пропс `rail` показывает у меню тонкий интерактивный край, по клику на который меню сворачивается и разворачивается. Рейка отрисовывается, только когда `collapsible` не равен `none`.

```vue
<template>
  <B24Sidebar rail collapsible="icon" title="Навигация">
<Placeholder class="h-full" />
</B24Sidebar>
</template>
```

### Закрытие

Пропс `close` показывает в шапке меню кнопку закрытия. Кнопка отрисовывается, только когда `collapsible` не равен `none`.

Чтобы настроить её, передайте любые свойства компонента [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md).

```vue
<template>
  <B24Sidebar close rail collapsible="icon" title="Навигация">
<Placeholder class="h-full" />
</B24Sidebar>
</template>
```

### Иконка закрытия

Пропс `close-icon` меняет [иконку](https://bitrix24.github.io/b24icons/icons/) кнопки закрытия.

```vue
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24Sidebar close :close-icon="RocketIcon" rail collapsible="icon" side="right" title="Навигация">
<Placeholder class="h-full" />
</B24Sidebar>
</template>
```

### Контрольная точка `2.15+`

Пропс `breakpoint` задаёт контрольную точку, ниже которой меню отрисовывается как меню-оверлей. По умолчанию `lg`.

```vue
<template>
  <B24Sidebar breakpoint="xl" />
</template>
```

> [!NOTE]
> Значения соответствуют стандартным контрольным точкам Tailwind CSS. Свои значения `--breakpoint-*` не учитываются.

### Режим

Пропс `mode` меняет режим меню на мобильных. По умолчанию `slideover`.

```vue [SidebarModeExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem, SidebarProps } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'

// В примере пропсы игнорируем
defineProps<Pick<SidebarProps, 'mode'>>()

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div class="flex flex-1">
    <B24Sidebar v-model:open="open" :mode="mode" title="Навигация">
      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center px-4 border-b border-default">
        <B24Button
          :icon="OpenChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

> [!TIP]
> See: #props
> Пропс `menu` настраивает меню; оно подстраивается под выбранный режим.

## Примеры

### Управление открытием

Состоянием открытия управляют пропс `open` или директива `v-model:open`. На десктопе она переключает «развёрнуто / свёрнуто», на мобильных — открывает и закрывает выезжающее меню.

```vue [SidebarOpenExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'

const open = ref(true)

defineShortcuts({
  o: () => open.value = !open.value
})

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div class="flex flex-1">
    <B24Sidebar v-model:open="open" title="Навигация" collapsible="icon">
      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center px-4 border-b border-default">
        <B24Button
          :icon="OpenChatIcon"
          color="air-tertiary"
          :aria-label="open ? 'Закрыть боковое меню' : 'Открыть боковое меню'"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

> [!NOTE]
> В этом примере с помощью [`defineShortcuts`](https://b24-ui.bx-shef.by/raw/docs/composables/define-shortcuts.md) Sidebar переключается по нажатию <kbd value="O">
> </kbd>
> .

### Сохранение состояния

Чтобы сохранять состояние меню между перезагрузками страницы, используйте вместо `ref` [`useLocalStorage`](https://vueuse.org/core/useLocalStorage/) из VueUse или [`useCookie`](https://nuxt.com/docs/4.x/api/composables/use-cookie).

```vue [SidebarPersistExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem } from '@bxshefby/b24ui-nuxt'
import { useLocalStorage } from '@vueuse/core'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'

const open = useLocalStorage('sidebar-open', true)

defineShortcuts({
  o: () => open.value = !open.value
})

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div class="flex flex-1">
    <B24Sidebar v-model:open="open" title="Навигация" collapsible="icon">
      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center px-4 border-b border-default">
        <B24Button
          :icon="OpenChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

> [!NOTE]
> Единственное отличие от предыдущего примера — `ref(true)` заменён на `useLocalStorage('sidebar-open', true)`.

### С нестандартной шириной

Ширину меню задаёт CSS-переменная `--sidebar-width` (по умолчанию `16rem`), а ширину свёрнутого меню с иконками — `--sidebar-width-icon` (по умолчанию `4rem`).

Переопределить их можно глобально в CSS или для отдельного экземпляра через атрибут `style`.

```vue [SidebarWidthExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div class="flex flex-1">
    <B24Sidebar
      v-model:open="open"
      collapsible="icon"
      :style="{ '--sidebar-width': '20rem' }"
    >
      <B24NavigationMenu
        :items="items"
        orientation="vertical"
        :b24ui="{ link: 'p-1.5 overflow-hidden' }"
      />
    </B24Sidebar>

    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center px-4 border-b border-default">
        <B24Button
          :icon="OpenChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

### С шапкой

Чтобы расположить меню под [Header](https://b24-ui.bx-shef.by/raw/docs/components/header.md), настройте `gap` и `container` через пропс `b24ui`.

```vue [SidebarHeaderExample.vue]
<script setup lang="ts">
import type { NavigationMenuItem } from '@bxshefby/b24ui-nuxt'
import HomeIcon from '@bitrix24/b24icons-vue/outline/HomeIcon'
import MailIcon from '@bitrix24/b24icons-vue/outline/MailIcon'
import ContactIcon from '@bitrix24/b24icons-vue/outline/ContactIcon'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'

const open = ref(true)

const items: NavigationMenuItem[] = [
  {
    label: 'Главная',
    icon: HomeIcon,
    active: true
  },
  {
    label: 'Входящие',
    icon: MailIcon,
    badge: '4'
  },
  {
    label: 'Контакты',
    icon: ContactIcon
  }
]
</script>

<template>
  <div class="flex flex-col flex-1">
    <B24Header title="Заголовок" toggle-side="left" :b24ui="{ container: 'px-4!' }">
      <template #toggle>
        <B24Button
          :icon="HamburgerMenuIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </template>
    </B24Header>

    <div class="flex flex-1 min-h-0">
      <B24Sidebar
        v-model:open="open"
        collapsible="icon"
        :b24ui="{
          gap: 'h-[calc(100%-var(--b24ui-header-height))]',
          container: 'absolute top-(--b24ui-header-height) bottom-0 h-[calc(100%-var(--b24ui-header-height))]'
        }"
      >
        <B24NavigationMenu
          :items="items"
          orientation="vertical"
          :b24ui="{ link: 'p-1.5 overflow-hidden' }"
        />
      </B24Sidebar>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>
  </div>
</template>
```

> [!NOTE]
> Переменная `--b24ui-header-height` по умолчанию равна `3.625rem` и используется в Header. Измените её, если у навигационной панели другая высота.

### С AI-чатом

Разместите меню справа вместе с [ChatMessages](https://b24-ui.bx-shef.by/raw/docs/components/chat-messages.md) и [ChatPrompt](https://b24-ui.bx-shef.by/raw/docs/components/chat-prompt.md), чтобы получить панель AI-чата.

```vue [SidebarChatExample.vue]
<script setup lang="ts">
import type { ChatMessageProps } from '@bxshefby/b24ui-nuxt'
import { isPartStreaming } from '@bxshefby/b24ui-nuxt/utils/ai'
import { Markdown } from '@comark/vue'
import shiki from '@comark/vue/plugins/shiki'
import OpenChatIcon from '@bitrix24/b24icons-vue/outline/OpenChatIcon'

const open = ref(true)
const input = ref('')

const messages = ref<ChatMessageProps[]>([
  {
    id: '1',
    role: 'user',
    parts: [{ type: 'text', text: 'Что такое Bitrix24 UI?' }]
  },
  {
    id: '2',
    role: 'assistant',
    parts: [{ type: 'text', text: 'Bitrix24 UI — библиотека Vue-компонентов на основе Reka UI, Tailwind CSS и Tailwind Variants. Содержит 130+ доступных компонентов для создания современных веб-приложений.' }]
  }
])

// Статичная демонстрация: ничего никуда не отправляется. Замените это вызовом своего эндпоинта.
function onSubmit() {
  const text = input.value.trim()
  if (!text) return

  messages.value.push(
    { id: `${Date.now()}-user`, role: 'user', parts: [{ type: 'text', text }] },
    { id: `${Date.now()}-assistant`, role: 'assistant', parts: [{ type: 'text', text: 'Эта демонстрация статичная, поэтому ничего не отправляется. Чтобы получать настоящие ответы, подключите промпт к своему эндпоинту — как это сделать, показано на странице Chat.' }] }
  )

  input.value = ''
}

const b24ui = {
  prose: {
    p: { base: 'my-2 text-sm/6' },
    li: { base: 'my-0.5 text-sm/6' },
    ul: { base: 'my-2' },
    ol: { base: 'my-2' },
    h1: { base: 'text-xl mb-4' },
    h2: { base: 'text-lg mt-6 mb-3' },
    h3: { base: 'text-base mt-4 mb-2' },
    h4: { base: 'text-sm mt-3 mb-1.5' },
    code: { base: 'text-xs' },
    pre: { root: 'my-2', base: 'text-xs/5' },
    table: { root: 'my-2' },
    hr: { base: 'my-4' }
  }
}
</script>

<template>
  <div class="flex flex-1">
    <div class="flex-1 flex flex-col">
      <div class="h-(--b24ui-header-height) shrink-0 flex items-center justify-end px-4 border-b border-default">
        <B24Button
          :icon="OpenChatIcon"
          color="air-tertiary"
          aria-label="Переключить боковое меню"
          @click="open = !open"
        />
      </div>

      <div class="flex-1 p-4">
        <Placeholder class="size-full" />
      </div>
    </div>

    <B24Sidebar
      v-model:open="open"
      side="right"
      title="AI-чат"
      close
      :style="{ '--sidebar-width': '20rem' }"
      :b24ui="{ container: 'h-full' }"
    >
      <B24Theme :b24ui="b24ui">
        <B24ChatMessages
          :messages="messages"
          status="ready"
          compact
          :user="{ b24ui: { text: 'text-sm/6' } }"
          class="px-0"
        >
          <template #part="{ part, message, streaming }">
            <Markdown
              v-if="part.type === 'text' && message.role === 'assistant'"
              :value="part.text"
              :streaming="isPartStreaming(part, streaming)"
              :plugins="[shiki()]"
              class="*:first:mt-0 *:last:mb-0"
            />
          </template>
        </B24ChatMessages>
      </B24Theme>

      <template #footer>
        <B24ChatPrompt
          v-model="input"
          :autofocus="false"
          variant="outline"
          size="sm"
          :b24ui="{ base: 'px-0' }"
          @submit="onSubmit"
        >
          <B24ChatPromptSubmit size="sm" status="ready" />
        </B24ChatPrompt>
      </template>
    </B24Sidebar>
  </div>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the Sidebar component
 */
interface SidebarProps {
  /**
   * The element or component this component should render as.
   * @default 'aside'
   */
  as?: any;
  /**
   * The visual variant of the sidebar.
   * @default 'sidebar'
   */
  variant?: "floating" | "sidebar" | "inset" | undefined;
  /**
   * The collapse behavior of the sidebar.
   * - `offcanvas`: The sidebar slides out of view completely.
   * - `icon`: The sidebar shrinks to icon-only width.
   * - `none`: The sidebar is not collapsible.
   * @default 'offcanvas'
   */
  collapsible?: "offcanvas" | "icon" | "none" | undefined;
  /**
   * The side to render the sidebar on.
   * @default 'left'
   */
  side?: "left" | "right" | undefined;
  /**
   * The title displayed in the sidebar header.
   */
  title?: string | undefined;
  /**
   * The description displayed in the sidebar header.
   */
  description?: string | undefined;
  /**
   * Display a close button to collapse the sidebar.
   * Only renders when `collapsible` is not `none`.
   * `{ size: 'md', color: 'neutral', variant: 'ghost' }`
   * @default false
   */
  close?: boolean | Omit<ButtonProps, LinkPropsKeys> | undefined;
  /**
   * The icon displayed in the close button.
   * @default icons.close
   */
  closeIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Display a rail on the sidebar edge to toggle collapse.
   * Only renders when `collapsible` is not `none`.
   * @default false
   */
  rail?: boolean | undefined;
  /**
   * Animate the sidebar when collapsing or expanding.
   * @default true
   */
  transition?: boolean | undefined;
  /**
   * The breakpoint below which the sidebar renders as a menu.
   * @default 'lg'
   */
  breakpoint?: "sm" | "md" | "lg" | "xl" | "2xl" | undefined;
  /**
   * The mode of the sidebar menu on mobile.
   * @default 'slideover'
   */
  mode?: T | undefined;
  /**
   * The props for the sidebar menu component on mobile.
   */
  menu?: SidebarMenu<T> | undefined;
  b24ui?: { root?: SlotClass; gap?: SlotClass; container?: SlotClass; inner?: SlotClass; header?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; actions?: SlotClass; close?: SlotClass; body?: SlotClass; footer?: SlotClass; rail?: SlotClass; content?: SlotClass; overlay?: SlotClass; } | undefined;
  /**
   * @default true
   */
  open?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Sidebar component
 */
interface SidebarSlots {
  header(): any;
  title(): any;
  description(): any;
  actions(): any;
  close(): any;
  default(): any;
  footer(): any;
  rail(): any;
  content(): any;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    sidebar: {
      slots: {
        root: 'peer [--sidebar-width:15rem] [--sidebar-width-icon:4.5rem]',
        gap: 'relative w-(--sidebar-width) bg-transparent',
        container: 'fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width)',
        inner: 'flex size-full flex-col overflow-hidden divide-y divide-default',
        header: 'flex items-center gap-1.5 overflow-hidden px-4 min-h-(--b24ui-header-height)',
        wrapper: 'min-w-0 flex-1',
        title: 'text-label font-semibold truncate',
        description: 'text-muted text-sm truncate',
        actions: 'flex items-center gap-1.5 shrink-0',
        close: '',
        body: 'flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4',
        footer: 'flex items-center gap-1.5 overflow-hidden p-4',
        rail: 'absolute inset-y-0 z-20 hidden w-4 after:absolute after:inset-y-0 after:left-1/2 after:w-px hover:after:bg-(--ui-color-divider-accent) after:transition-colors',
        content: '',
        overlay: ''
      },
      variants: {
        transition: {
          true: {
            gap: 'transition-[width] duration-200 ease-out motion-reduce:transition-none',
            container: 'transition-[inset-inline-start,inset-inline-end,width] duration-200 ease-out motion-reduce:transition-none',
            rail: 'transition-all ease-out'
          }
        },
        breakpoint: {
          sm: {
            container: 'sm:flex',
            rail: 'sm:flex'
          },
          md: {
            container: 'md:flex',
            rail: 'md:flex'
          },
          lg: {
            container: 'lg:flex',
            rail: 'lg:flex'
          },
          xl: {
            container: 'xl:flex',
            rail: 'xl:flex'
          },
          '2xl': {
            container: '2xl:flex',
            rail: '2xl:flex'
          }
        },
        side: {
          left: {
            container: 'start-0 border-e border-default',
            rail: 'end-0 translate-x-1/2 rtl:-translate-x-1/2'
          },
          right: {
            container: 'end-0 border-s border-default',
            rail: '-start-px -translate-x-1/2 rtl:translate-x-1/2'
          }
        },
        collapsible: {
          offcanvas: {
            root: 'group/sidebar hidden',
            gap: 'data-[state=collapsed]:w-0'
          },
          icon: {
            root: 'group/sidebar hidden',
            gap: 'data-[state=collapsed]:w-(--sidebar-width-icon)',
            container: 'data-[state=collapsed]:w-(--sidebar-width-icon)',
            actions: 'group-data-[state=collapsed]/sidebar:hidden',
            body: 'group-data-[state=collapsed]/sidebar:overflow-hidden'
          },
          none: {
            root: 'h-full w-(--sidebar-width)'
          }
        },
        variant: {
          sidebar: {},
          floating: {
            container: 'p-4 border-transparent',
            inner: 'rounded-lg ring ring-default shadow-lg',
            rail: 'inset-y-4'
          },
          inset: {
            container: 'py-4 border-transparent',
            inner: 'divide-transparent',
            rail: 'inset-y-4'
          }
        }
      },
      compoundVariants: [
        {
          breakpoint: 'sm',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            root: 'sm:block'
          }
        },
        {
          breakpoint: 'md',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            root: 'md:block'
          }
        },
        {
          breakpoint: 'lg',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            root: 'lg:block'
          }
        },
        {
          breakpoint: 'xl',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            root: 'xl:block'
          }
        },
        {
          breakpoint: '2xl',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            root: '2xl:block'
          }
        },
        {
          side: 'left',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            rail: 'cursor-w-resize rtl:cursor-e-resize data-[state=collapsed]:cursor-e-resize data-[state=collapsed]:rtl:cursor-w-resize'
          }
        },
        {
          side: 'right',
          collapsible: [
            'offcanvas',
            'icon'
          ],
          class: {
            rail: 'cursor-e-resize rtl:cursor-w-resize data-[state=collapsed]:cursor-w-resize data-[state=collapsed]:rtl:cursor-e-resize'
          }
        },
        {
          side: 'left',
          collapsible: 'none',
          class: {
            root: 'border-e border-default'
          }
        },
        {
          side: 'right',
          collapsible: 'none',
          class: {
            root: 'border-s border-default'
          }
        },
        {
          side: 'left',
          collapsible: 'offcanvas',
          class: {
            container: 'data-[state=collapsed]:-start-(--sidebar-width)'
          }
        },
        {
          side: 'right',
          collapsible: 'offcanvas',
          class: {
            container: 'data-[state=collapsed]:-end-(--sidebar-width)'
          }
        },
        {
          variant: 'floating',
          collapsible: 'icon',
          class: {
            gap: 'data-[state=collapsed]:w-[calc(var(--sidebar-width-icon)+--spacing(6.5))]',
            container: 'data-[state=collapsed]:w-[calc(var(--sidebar-width-icon)+--spacing(6.5)+2px)]'
          }
        },
        {
          variant: 'floating',
          collapsible: 'none',
          class: {
            root: 'p-4 border-0'
          }
        },
        {
          variant: 'inset',
          collapsible: 'none',
          class: {
            root: 'py-4 border-0'
          }
        },
        {
          variant: 'floating',
          side: 'left',
          class: {
            rail: 'end-4'
          }
        },
        {
          variant: 'floating',
          side: 'right',
          class: {
            rail: 'start-[calc(--spacing(4)-1px)]'
          }
        }
      ]
    }
  }
})
```

## Sitemap

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