---
title: "Drawer"
description: "Выдвижная шторка с плавными анимациями появления и скрытия."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/drawer"
---
# Drawer

> Выдвижная шторка с плавными анимациями появления и скрытия.

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

Поместите в слот по умолчанию Drawer компонент [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md) или любой другой.

Затем слот `#content` добавляет содержимое, которое показывается при открытом Drawer.

```vue
<template>
  <B24Drawer>
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

Слоты `#header`, `#body` и `#footer` настраивают содержимое Drawer.

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

Пропс `title` задаёт заголовок в шапке Drawer.

```vue
<template>
  <B24Drawer title="Drawer с заголовком">
<B24Button label="Открыть" />

  <template #body>
    
<Placeholder class="h-48" />

  </template>

</B24Drawer>
</template>
```

### Описание

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

```vue
<template>
  <B24Drawer title="Drawer с описанием" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<B24Button label="Открыть" />

  <template #body>
    
<Placeholder class="h-48" />

  </template>

</B24Drawer>
</template>
```

### Направление

Пропс `direction` задаёт направление Drawer. По умолчанию `bottom`.

```vue
<template>
  <B24Drawer direction="right">
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="min-w-96 min-h-96 size-full m-4" />

  </template>

</B24Drawer>
</template>
```

### Отступ от краёв

Пропс `inset` отодвигает Drawer от краёв.

```vue
<template>
  <B24Drawer direction="right" inset>
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="min-w-96 min-h-96 size-full m-4" />

  </template>

</B24Drawer>
</template>
```

### Ручка

Пропс `handle` определяет, есть ли у Drawer ручка. По умолчанию `true`.

```vue
<template>
  <B24Drawer :handle="false">
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

### Только ручка

Пропс `handle-only` разрешает перетаскивать Drawer только за ручку.

```vue
<template>
  <B24Drawer handle-only>
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

### Оверлей

Пропс `overlay` определяет, есть ли у Drawer оверлей. По умолчанию `true`.

```vue
<template>
  <B24Drawer :overlay="false">
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

### Модальный режим

Пропс `modal` определяет, блокирует ли Drawer взаимодействие с контентом вне него. По умолчанию `true`.

> [!NOTE]
> Если `modal` равен `false`, оверлей отключается автоматически, и контент вне Drawer остаётся доступным.

```vue
<template>
  <B24Drawer :modal="false">
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

### Закрытие вне Drawer

Пропс `dismissible` определяет, закрывается ли Drawer по щелчку вне его или по клавише Esc. По умолчанию `true`.

> [!NOTE]
> Когда пользователь пытается закрыть Drawer, срабатывает событие `close:prevent`.

> [!TIP]
> Чтобы фон при открытом Drawer оставался доступным и Drawer не закрывался, объедините `modal: false` и `dismissible: false`.

```vue [DrawerDismissibleExample.vue]
<script setup lang="ts">
import Cross50Icon from '@bitrix24/b24icons-vue/actions/Cross50Icon'

const open = ref(false)
</script>

<template>
  <B24Drawer v-model:open="open" :dismissible="false" :modal="false" :handle="false">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <div class="flex items-center justify-between gap-4 mb-4">
        <ProseH2 class="mb-0">
          Drawer без закрытия по действию вне окна
        </ProseH2>

        <B24Button color="air-tertiary" :icon="Cross50Icon" @click="open = false" />
      </div>

      <Placeholder class="size-full min-h-48" />
    </template>
  </B24Drawer>
</template>
```

### Масштабирование фона

Пропс `should-scale-background` масштабирует фон при открытом Drawer и создаёт эффект глубины. Пропс `set-background-color-on-scale` со значением `false` запрещает менять цвет фона.

```vue
<template>
  <B24Drawer should-scale-background set-background-color-on-scale>
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

> [!WARNING]
> Чтобы это работало, добавьте директиву `data-vaul-drawer-wrapper` родительскому элементу приложения.
> ```vue [app.vue]
> <template>
>   <B24App>
>     <div class="bg-default" data-vaul-drawer-wrapper>
>       <NuxtLayout>
>         <NuxtPage />
>       </NuxtLayout>
>     </div>
>   </B24App>
> </template>
> ```
> ```ts [nuxt.config.ts]
> export default defineNuxtConfig({
>   app: {
>     rootAttrs: {
>       'data-vaul-drawer-wrapper': '',
>       'class': 'bg-default'
>     }
>   }
> })
> ```

### Без стилей для body `2.15+`

Пропс `no-body-styles` запрещает Drawer применять стили к элементу `<body>`: например, `pointer-events: none`, который блокирует взаимодействие со страницей, пока Drawer открыт.

> [!NOTE]
> При включённом `overlay` прокрутка body всё равно блокируется. Чтобы страница оставалась интерактивной, объедините `no-body-styles` и `overlay: false`.

```vue
<template>
  <B24Drawer no-body-styles :overlay="false">
<B24Button label="Открыть" />

  <template #content>
    
<Placeholder class="h-48 m-4" />

  </template>

</B24Drawer>
</template>
```

## Примеры

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

Состоянием открытия управляют пропс `default-open` или директива `v-model:open`.

```vue [DrawerOpenExample.vue]
<script setup lang="ts">
const open = ref(false)

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

<template>
  <B24Drawer v-model:open="open">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #content>
      <Placeholder class="h-48 m-4" />
    </template>
  </B24Drawer>
</template>
```

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

> [!TIP]
> Так триггер можно вынести за пределы Drawer или убрать совсем.

### Адаптивный Drawer

Например, на десктопе можно показывать компонент [Modal](https://b24-ui.bx-shef.by/raw/docs/components/modal.md), а на мобильных устройствах — Drawer.

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

const { screen } = useDevice()

const [DefineFormTemplate, ReuseFormTemplate] = createReusableTemplate()
const open = ref(false)

const state = reactive({
  email: undefined
})

const title = 'Изменить профиль'
const description = 'Здесь можно изменить данные профиля. Нажмите «Сохранить», когда закончите.'
</script>

<template>
  <DefineFormTemplate>
    <B24Form :state="state" class="space-y-4">
      <B24FormField label="Email" name="email" required>
        <B24Input v-model="state.email" placeholder="you@example.com" required />
      </B24FormField>

      <B24Button label="Сохранить изменения" color="air-primary-success" type="submit" />
    </B24Form>
  </DefineFormTemplate>

  <B24Modal v-if="!screen.isMobile" v-model:open="open" :title="title" :description="description">
    <B24Button label="Изменить профиль" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </B24Modal>

  <B24Drawer v-else v-model:open="open" :title="title" :description="description">
    <B24Button label="Изменить профиль" />

    <template #body>
      <ReuseFormTemplate />
    </template>
  </B24Drawer>
</template>
```

### Вложенные Drawer

Drawer можно вкладывать друг в друга пропсом `nested`.

```vue [DrawerNestedExample.vue]
<template>
  <B24Drawer :b24ui="{ content: 'h-full' }">
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #footer>
      <B24Drawer nested :b24ui="{ content: 'h-full' }">
        <B24Button label="Открыть вложенное" />

        <template #content>
          <Placeholder class="flex-1 m-4" />
        </template>
      </B24Drawer>
    </template>
  </B24Drawer>
</template>
```

### Слот footer

Слот `#footer` добавляет контент после тела Drawer.

```vue [DrawerFooterSlotExample.vue]
<script setup lang="ts">
const open = ref(false)
</script>

<template>
  <B24Drawer
    v-model:open="open"
    title="Drawer с подвалом"
    description="Пригодится, когда в Drawer нужна форма."
    :b24ui="{ container: 'max-w-xl mx-auto' }"
  >
    <B24Button label="Открыть" use-dropdown :b24ui="{ trailingIcon: 'rotate-180' }" />

    <template #body>
      <Placeholder class="h-48" />
    </template>

    <template #footer>
      <B24Button label="Отправить" color="air-primary-success" />
      <B24Button label="Отмена" @click="open = false" />
    </template>
  </B24Drawer>
</template>
```

### С командной палитрой

Внутри содержимого Drawer можно использовать [CommandPalette](https://b24-ui.bx-shef.by/raw/docs/components/command-palette.md).

```vue [DrawerCommandPaletteExample.vue]
<script setup lang="ts">
import PersonSearchIcon from '@bitrix24/b24icons-vue/outline/PersonSearchIcon'

const searchTerm = ref('')

const { data: users, status, execute } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'drawer-command-palette-users',
  query: { q: searchTerm },
  transform: (data: { id: number, name: string, email: string }[]) => {
    return data?.map(user => ({ id: user.id, label: user.name, suffix: user.email, avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const } })) || []
  },
  immediate: false
})

const groups = computed(() => [{
  id: 'users',
  label: searchTerm.value ? `Пользователи по запросу «${searchTerm.value}»...` : 'Пользователи',
  items: users.value || [],
  ignoreFilter: true
}])

function onOpen() {
  if (!users.value?.length) {
    execute()
  }
}
</script>

<template>
  <B24Drawer :handle="false" @update:open="onOpen">
    <B24Button
      label="Найдите пользователей..."
      :icon="PersonSearchIcon"
      use-dropdown
      :b24ui="{ trailingIcon: 'rotate-180' }"
    />

    <template #content>
      <B24CommandPalette
        v-model:search-term="searchTerm"
        :loading="status === 'pending'"
        :groups="groups"
        placeholder="Найдите пользователей..."
        class="h-80"
      />
    </template>
  </B24Drawer>
</template>
```

> [!NOTE]
> В этом примере `useLazyFetch` с `immediate: false` загружает данные только при открытии Drawer.

## API

### Пропсы

```ts
/**
 * Props for the Drawer component
 */
interface DrawerProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  title?: string | undefined;
  description?: string | undefined;
  /**
   * Whether to inset the drawer from the edges.
   * @default false
   */
  inset?: boolean | undefined;
  /**
   * The content of the drawer.
   */
  content?: Omit<DialogContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DialogContentImplEmits>> | undefined;
  /**
   * Render an overlay behind the drawer.
   * @default true
   */
  overlay?: boolean | undefined;
  /**
   * Render an overlay blur behind the modal.
   * `auto` use `motion-safe`.
   * @default 'auto'
   */
  overlayBlur?: "auto" | "on" | "off" | undefined;
  /**
   * Render a handle on the drawer.
   * @default true
   */
  handle?: boolean | undefined;
  /**
   * Render the drawer in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * Whether the drawer is nested in another drawer.
   * @default false
   */
  nested?: boolean | undefined;
  /**
   * @default true
   */
  scrollbarThin?: boolean | undefined;
  /**
   * Display a close button to dismiss the drawer.
   * `{ size: 'md', color: 'air-tertiary-no-accent' }`
   * @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;
  b24ui?: { overlay?: SlotClass; content?: SlotClass; handle?: SlotClass; container?: SlotClass; header?: SlotClass; wrapper?: SlotClass; title?: SlotClass; description?: SlotClass; actions?: SlotClass; body?: SlotClass; footer?: SlotClass; close?: SlotClass; } | undefined;
  activeSnapPoint?: null | string | number | undefined;
  /**
   * Number between 0 and 1 that determines when the drawer should be closed.
   * Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.
   */
  closeThreshold?: number | undefined;
  shouldScaleBackground?: boolean | undefined;
  /**
   * When `false` we don't change body's background color when the drawer is open.
   */
  setBackgroundColorOnScale?: boolean | undefined;
  /**
   * Duration for which the drawer is not draggable after scrolling content inside of the drawer.
   */
  scrollLockTimeout?: number | undefined;
  /**
   * When `true`, don't move the drawer upwards if there's space, but rather only change it's height so it's fully scrollable when the keyboard is open
   */
  fixed?: boolean | undefined;
  /**
   * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
   * Use this in combination with the `open` prop, otherwise you won't be able to open/close the drawer.
   * @default true
   */
  dismissible?: boolean | undefined;
  /**
   * When `false` it allows to interact with elements outside of the drawer without closing it.
   * @default true
   */
  modal?: boolean | undefined;
  open?: boolean | undefined;
  /**
   * Opened by default, skips initial enter animation. Still reacts to `open` state changes
   */
  defaultOpen?: boolean | undefined;
  /**
   * Direction of the drawer. Can be `top` or `bottom`, `left`, `right`.
   * @default 'bottom'
   */
  direction?: "bottom" | "top" | "left" | "right" | undefined;
  /**
   * When `true` the `body` doesn't get any styles assigned from Vaul
   */
  noBodyStyles?: boolean | undefined;
  /**
   * When `true` only allows the drawer to be dragged by the `<Drawer.Handle />` component.
   */
  handleOnly?: boolean | undefined;
  preventScrollRestoration?: boolean | undefined;
  /**
   * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
   * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
   * You can also use px values, which doesn't take screen height into account.
   */
  snapPoints?: (string | number)[] | undefined;
}
```

### Слоты

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

### События

```ts
/**
 * Emitted events for the Drawer component
 */
interface DrawerEmits {
  close: (payload: []) => void;
  drag: (payload: [percentageDragged: number]) => void;
  after:leave: (payload: []) => void;
  after:enter: (payload: []) => void;
  close:prevent: (payload: []) => void;
  release: (payload: [open: boolean]) => void;
  update:open: (payload: [open: boolean]) => void;
  update:activeSnapPoint: (payload: [val: string | number]) => void;
  animationEnd: (payload: [open: boolean]) => void;
}
```

## Доступность `2.14+`

При открытии фокус на один такт уходит с триггера, и только потом его перехватывает ловушка фокуса диалога. Так обходится [ошибка тайминга в reka-ui](https://github.com/unovue/reka-ui/issues/1280), из-за которой браузер отказывается применять `aria-hidden` и пишет в консоль *«Blocked aria-hidden on an element because its descendant retained focus»*.

Фокус возвращается туда, где он был до открытия, в том числе когда компонент открывают программно, а не через слот триггера. Скринридеры, которые сразу озвучивают смену фокуса (прежде всего VoiceOver), могут ненадолго озвучить заголовок страницы раньше заголовка диалога.

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    drawer: {
      slots: {
        overlay: 'fixed inset-0',
        content: 'fixed base-mode bg-(--ui-color-bg-content-primary) flex focus:outline-none ring ring-(--ui-color-divider-default)',
        handle: 'shrink-0 !bg-(--ui-color-divider-default) transition-opacity',
        container: 'w-full flex flex-col gap-4 p-4 overflow-y-auto',
        header: 'flex items-center gap-1.5 min-h-8',
        wrapper: 'min-w-0 flex-1',
        title: 'font-[family-name:var(--ui-font-family-primary)] text-label font-(--ui-font-weight-medium) mb-0 text-[calc(var(--ui-font-size-2xl)+2px)]/(--ui-font-size-2xl)',
        description: 'mt-1 text-description text-(length:--ui-font-size-sm)',
        actions: 'flex items-center gap-1.5 shrink-0 ms-auto',
        body: 'flex-1',
        footer: 'flex flex-col gap-1.5',
        close: ''
      },
      variants: {
        overlayBlur: {
          auto: {
            overlay: 'motion-safe:backdrop-blur-sm'
          },
          on: {
            overlay: 'backdrop-blur-sm'
          },
          off: {
            overlay: ''
          }
        },
        scrollbarThin: {
          true: {
            body: 'scrollbar-thin'
          }
        },
        overlay: {
          true: {
            overlay: 'bg-[#003366]/20'
          }
        },
        direction: {
          top: {
            content: 'mb-24 flex-col-reverse',
            handle: 'mb-4'
          },
          right: {
            content: 'flex-row rtl:flex-row-reverse',
            handle: '!ml-4'
          },
          bottom: {
            content: 'mt-24 flex-col',
            handle: 'mt-4'
          },
          left: {
            content: 'flex-row-reverse rtl:flex-row',
            handle: '!mr-4'
          }
        },
        inset: {
          true: {
            content: 'rounded-lg after:hidden overflow-hidden [--initial-transform:calc(100%+1.5rem)]'
          }
        },
        snapPoints: {
          true: ''
        }
      },
      compoundVariants: [
        {
          direction: [
            'top',
            'bottom'
          ],
          class: {
            content: 'h-auto max-h-[96%]',
            handle: '!w-12 !h-1.5 mx-auto'
          }
        },
        {
          direction: [
            'top',
            'bottom'
          ],
          snapPoints: true,
          class: {
            content: 'h-full'
          }
        },
        {
          direction: [
            'right',
            'left'
          ],
          class: {
            content: 'w-auto max-w-[calc(100%-2rem)]',
            handle: '!h-12 !w-1.5 mt-auto mb-auto'
          }
        },
        {
          direction: [
            'right',
            'left'
          ],
          snapPoints: true,
          class: {
            content: 'w-full'
          }
        },
        {
          direction: 'top',
          inset: true,
          class: {
            content: 'inset-x-4 top-4'
          }
        },
        {
          direction: 'top',
          inset: false,
          class: {
            content: 'inset-x-0 top-0 rounded-b-lg'
          }
        },
        {
          direction: 'bottom',
          inset: true,
          class: {
            content: 'inset-x-4 bottom-4'
          }
        },
        {
          direction: 'bottom',
          inset: false,
          class: {
            content: 'inset-x-0 bottom-0 rounded-t-lg'
          }
        },
        {
          direction: 'left',
          inset: true,
          class: {
            content: 'inset-y-4 left-4'
          }
        },
        {
          direction: 'left',
          inset: false,
          class: {
            content: 'inset-y-0 left-0 rounded-r-lg'
          }
        },
        {
          direction: 'right',
          inset: true,
          class: {
            content: 'inset-y-4 right-4'
          }
        },
        {
          direction: 'right',
          inset: false,
          class: {
            content: 'inset-y-0 right-0 rounded-l-lg'
          }
        }
      ]
    }
  }
})
```

## Sitemap

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