---
title: "DropdownMenu"
description: "Контекстное меню действий, которое открывается по щелчку на элементе."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/dropdown-menu"
---
# DropdownMenu

> Контекстное меню действий, которое открывается по щелчку на элементе.

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

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

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[][]>([
  [
    {
      label: 'Bitrix24',
      avatar: {
        src: 'https://github.com/bitrix24.png',
        loading: 'lazy'
      },
      type: 'label'
    }
  ],
  [
    {
      label: 'Профиль'
    },
    {
      label: 'Оплата'
    },
    {
      label: 'Настройки',
      kbds: [
        ','
      ]
    },
    {
      label: 'Горячие клавиши'
    }
  ],
  [
    {
      label: 'Команда',
      filter: {
        placeholder: 'Найти участника...'
      },
      children: [
        [
          {
            label: 'Bitrix24',
            avatar: {
              src: 'https://github.com/bitrix24.png',
              loading: 'lazy'
            }
          },
          {
            label: 'Bitrix',
            avatar: {
              src: 'https://github.com/bitrix-tools.png',
              loading: 'lazy'
            }
          }
        ]
      ]
    },
    {
      label: 'Пригласить пользователей',
      children: [
        [
          {
            label: 'Почта'
          },
          {
            label: 'Сообщение'
          }
        ],
        [
          {
            label: 'Ещё',
            children: [
              {
                label: 'Импорт из Slack'
              },
              {
                label: 'Импорт из Trello'
              },
              {
                label: 'Импорт из Asana'
              }
            ]
          }
        ]
      ]
    },
    {
      label: 'Новая команда',
      kbds: [
        'meta',
        'n'
      ]
    }
  ],
  [
    {
      label: 'GitHub',
      to: 'https://github.com/bitrix24/b24ui',
      target: '_blank'
    },
    {
      label: 'Поддержка',
      to: '/docs/components/dropdown-menu/'
    },
    {
      label: 'API',
      disabled: true
    }
  ],
  [
    {
      label: 'Выйти',
      color: 'air-primary-alert',
      kbds: [
        'shift',
        'meta',
        'q'
      ]
    }
  ]
])
</script>

<template>
  <B24DropdownMenu :items="items">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

### Элементы

Пропс `items` — массив объектов со свойствами:

- `label?: string`
- `icon?: IconComponent`
- `avatar?: AvatarProps`
- `kbds?: string[] | KbdProps[]`
- [`type?: "link" | "label" | "separator" | "checkbox"`](#with-checkbox-items)
- [`color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-primary-warning"`](#with-color-items)
- [`checked?: boolean`](#with-checkbox-items)
- `disabled?: boolean`
- [`slot?: string`](#with-custom-slot)
- `onSelect?: (e: Event) => void`
- [`onUpdateChecked?: (checked: boolean) => void`](#with-checkbox-items)
- `children?: DropdownMenuItem[] | DropdownMenuItem[][]`
- [`filter?: boolean | InputProps`](#with-filter-items)
- `filterFields?: string[]`
- `ignoreFilter?: boolean`
- `class?: any`
- `b24ui?: { item?: ClassNameValue, label?: ClassNameValue, separator?: ClassNameValue, itemLeadingIcon?: ClassNameValue, itemLeadingAvatarSize?: ClassNameValue, itemLeadingAvatar?: ClassNameValue, itemLabel?: ClassNameValue, itemLabelExternalIcon?: ClassNameValue, itemTrailing?: ClassNameValue, itemTrailingIcon?: ClassNameValue, itemTrailingKbds?: ClassNameValue, itemTrailingKbdsSize?: ClassNameValue }`

Можно передать любое свойство компонента [Link](https://b24-ui.bx-shef.by/raw/docs/components/link.md#props): `to`, `target` и другие.

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[][]>([
  [
    {
      label: 'Bitrix24',
      avatar: {
        src: 'https://github.com/bitrix24.png',
        loading: 'lazy'
      },
      type: 'label'
    }
  ],
  [
    {
      label: 'Профиль'
    },
    {
      label: 'Оплата'
    },
    {
      label: 'Настройки',
      kbds: [
        ','
      ]
    },
    {
      label: 'Горячие клавиши'
    }
  ],
  [
    {
      label: 'Команда'
    },
    {
      label: 'Пригласить пользователей',
      children: [
        [
          {
            label: 'Почта'
          },
          {
            label: 'Сообщение'
          }
        ],
        [
          {
            label: 'Ещё',
            children: [
              {
                label: 'Импорт из Slack'
              },
              {
                label: 'Импорт из Trello'
              },
              {
                label: 'Импорт из Asana'
              }
            ]
          }
        ]
      ]
    },
    {
      label: 'Новая команда',
      kbds: [
        'meta',
        'n'
      ]
    }
  ],
  [
    {
      label: 'GitHub',
      to: 'https://github.com/bitrix24/b24ui',
      target: '_blank'
    },
    {
      label: 'Поддержка',
      to: '/docs/components/dropdown-menu/'
    },
    {
      label: 'API',
      disabled: true
    }
  ],
  [
    {
      label: 'Выйти',
      kbds: [
        'shift',
        'meta',
        'q'
      ]
    }
  ]
])
</script>

<template>
  <B24DropdownMenu :items="items">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

> [!NOTE]
> Чтобы получить отдельные группы элементов, передайте в `items` массив массивов.

> [!TIP]
> Чтобы создать вложенное меню, элемент может содержать массив `children` с такими же свойствами, как у `items`. Вложенным меню можно управлять через свойства `open`, `defaultOpen` и `content`.

### Содержимое

Пропс `content` управляет отрисовкой содержимого DropdownMenu: например, его `align` или `side`.

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[]>([
  {
    label: 'Профиль'
  },
  {
    label: 'Оплата'
  },
  {
    label: 'Настройки'
  }
])
</script>

<template>
  <B24DropdownMenu :items="items" :content="{align:'start',side:'bottom',sideOffset:8}">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

### Фильтр

Пропс `filter` показывает внутри DropdownMenu поле фильтра. По умолчанию `false`.

> [!NOTE]
> See: #with-ignore-filter
> Пропс `ignore-filter` отключает встроенный поиск, и вы используете свою логику поиска.

> [!NOTE]
> See: #with-filter-fields
> Пропс `filter-fields` задаёт поля, по которым идёт фильтрация. По умолчанию используется пропс `labelKey`.

Поле фильтра можно настроить любым свойством компонента [Input](https://b24-ui.bx-shef.by/raw/docs/components/input.md).

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[]>([
  {
    label: 'Профиль'
  },
  {
    label: 'Оплата'
  },
  {
    label: 'Настройки'
  },
  {
    label: 'Команда'
  },
  {
    label: 'Пригласить пользователей'
  },
  {
    label: 'Новая команда'
  }
])
</script>

<template>
  <B24DropdownMenu :items="items" filter :content="{align:'start'}" :b24ui="{content:'w-48'}">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

> [!TIP]
> See: #with-filter-items
> Фильтр можно включить и в отдельных вложенных меню: для этого используйте поле `filter` у элементов с `children`.

### Стрелка

Пропс `arrow` показывает у DropdownMenu стрелку.

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[]>([
  {
    label: 'Профиль'
  },
  {
    label: 'Оплата'
  },
  {
    label: 'Настройки'
  }
])
</script>

<template>
  <B24DropdownMenu arrow :items="items">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

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

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

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[]>([
  {
    label: 'Профиль'
  },
  {
    label: 'Оплата'
  },
  {
    label: 'Настройки'
  }
])
</script>

<template>
  <B24DropdownMenu :modal="false" :items="items" :b24ui="{content:'w-48'}">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

### Отключение

Пропс `disabled` отключает DropdownMenu.

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items = ref<DropdownMenuItem[]>([
  {
    label: 'Профиль'
  },
  {
    label: 'Оплата'
  },
  {
    label: 'Настройки'
  }
])
</script>

<template>
  <B24DropdownMenu disabled :items="items" :b24ui="{content:'w-48'}">
<B24Button label="Открыть" />
</B24DropdownMenu>
</template>
```

## Примеры

### С чекбоксами

Свойство `type` со значением `checkbox` вместе со свойствами `checked` и `onUpdateChecked` управляет отмеченным состоянием элемента.

```vue [DropdownMenuCheckboxItemsExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import CloudDownloadIcon from '@bitrix24/b24icons-vue/outline/CloudDownloadIcon'
import ClockWithArrowIcon from '@bitrix24/b24icons-vue/main/ClockWithArrowIcon'
import Bookmark2Icon from '@bitrix24/b24icons-vue/outline/Bookmark2Icon'
import WindowScreenIcon from '@bitrix24/b24icons-vue/social/WindowScreenIcon'

const showBookmarks = ref(true)
const showHistory = ref(false)
const showDownloads = ref(false)

const items = computed(() => [
  {
    label: 'Интерфейс',
    icon: WindowScreenIcon,
    type: 'label' as const
  },
  {
    label: 'Показывать закладки',
    icon: Bookmark2Icon,
    type: 'checkbox' as const,
    checked: showBookmarks.value,
    onUpdateChecked(checked: boolean) {
      showBookmarks.value = checked
    },
    onSelect(e: Event) {
      e.preventDefault()
    }
  },
  {
    label: 'Показывать историю',
    icon: ClockWithArrowIcon,
    type: 'checkbox' as const,
    checked: showHistory.value,
    onUpdateChecked(checked: boolean) {
      showHistory.value = checked
    }
  },
  {
    type: 'separator' as const
  },
  {
    label: 'Показывать загрузки',
    icon: CloudDownloadIcon,
    type: 'checkbox' as const,
    checked: showDownloads.value,
    onUpdateChecked(checked: boolean) {
      showDownloads.value = checked
    }
  }
] satisfies DropdownMenuItem[])
</script>

<template>
  <B24DropdownMenu :items="items" :content="{ align: 'start' }" :b24ui="{ content: 'w-48', viewport: 'w-48' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

> [!NOTE]
> Чтобы состояние `checked` у элементов было реактивным, оберните массив `items` в `computed`.

### С цветом

Свойство `color` выделяет отдельные элементы цветом.

```vue [DropdownMenuColorItemsExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import OpenedEyeIcon from '@bitrix24/b24icons-vue/main/OpenedEyeIcon'
import TrashBinIcon from '@bitrix24/b24icons-vue/main/TrashBinIcon'
import CopyPlatesIcon from '@bitrix24/b24icons-vue/actions/CopyPlatesIcon'
import PencilDrawIcon from '@bitrix24/b24icons-vue/actions/PencilDrawIcon'

const items: DropdownMenuItem[][] = [
  [
    {
      label: 'Просмотр',
      icon: OpenedEyeIcon
    },
    {
      label: 'Копировать',
      icon: CopyPlatesIcon
    },
    {
      label: 'Изменить',
      icon: PencilDrawIcon
    }
  ],
  [
    {
      label: 'Удалить',
      color: 'air-primary-alert' as const,
      icon: TrashBinIcon
    }
  ]
]
</script>

<template>
  <B24DropdownMenu :items="items" :b24ui="{ content: 'w-48', viewport: 'w-48' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

### С фильтром во вложенных меню

Свойство `filter` у элементов с `children` показывает поле фильтра внутри вложенного меню.

```vue [DropdownMenuFilterItemsExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import PaymentIcon from '@bitrix24/b24icons-vue/outline/PaymentIcon'
import Settings3Icon from '@bitrix24/b24icons-vue/actions/Settings3Icon'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'

const items: DropdownMenuItem[][] = [
  [
    {
      label: 'Профиль',
      icon: UserIcon
    }, {
      label: 'Оплата',
      icon: PaymentIcon
    }, {
      label: 'Настройки',
      icon: Settings3Icon
    }
  ],
  [
    {
      label: 'Команда',
      filter: {
        placeholder: 'Найдите участников...'
      },
      children: [
        {
          label: 'Bitrix24',
          avatar: { src: 'https://github.com/bitrix24.png', loading: 'lazy' as const }
        },
        {
          label: 'Bitrix',
          avatar: { src: 'https://github.com/bitrix-tools.png', loading: 'lazy' as const }
        }
      ]
    },
    {
      label: 'Пригласить пользователей',
      children: [
        {
          label: 'Пригласить по email'
        },
        {
          label: 'Пригласить по ссылке'
        },
        {
          label: 'Пригласить по SMS'
        },
        {
          label: 'Пригласить через WhatsApp'
        }
      ]
    },
    {
      label: 'Новая команда'
    }
  ]
]
</script>

<template>
  <B24DropdownMenu :items="items" :content="{ align: 'start' }" :b24ui="{ content: 'w-48', viewport: 'w-48' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

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

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

```vue [DropdownMenuOpenExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import PaymentIcon from '@bitrix24/b24icons-vue/outline/PaymentIcon'
import Settings3Icon from '@bitrix24/b24icons-vue/actions/Settings3Icon'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'

const open = ref(false)

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

const items: DropdownMenuItem[] = [
  {
    label: 'Профиль',
    icon: UserIcon,
    slot: 'profile' as const
  }, {
    label: 'Оплата',
    icon: PaymentIcon
  }, {
    label: 'Настройки',
    icon: Settings3Icon
  }
]
</script>

<template>
  <B24DropdownMenu v-model:open="open" :items="items" :b24ui="{ content: 'w-50', viewport: 'w-50' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

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

### Свой слот

Свойство `slot` настраивает отдельный элемент.

Вам будут доступны слоты:

- `#{{ item.slot }}`
- `#{{ item.slot }}-leading`
- `#{{ item.slot }}-label`
- `#{{ item.slot }}-trailing`

```vue [DropdownMenuCustomSlotExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import PaymentIcon from '@bitrix24/b24icons-vue/outline/PaymentIcon'
import Settings3Icon from '@bitrix24/b24icons-vue/actions/Settings3Icon'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import CloudWithCheckIcon from '@bitrix24/b24icons-vue/outline/CloudWithCheckIcon'

const items = [
  {
    label: 'Профиль',
    icon: UserIcon,
    slot: 'profile' as const
  }, {
    label: 'Оплата',
    icon: PaymentIcon
  }, {
    label: 'Настройки',
    icon: Settings3Icon
  }
] satisfies DropdownMenuItem[]
</script>

<template>
  <B24DropdownMenu :items="items" :b24ui="{ content: 'w-48', viewport: 'w-48' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />

    <template #profile-trailing>
      <CloudWithCheckIcon class="shrink-0 size-5 text-(--ui-color-accent-main-primary)" />
    </template>
  </B24DropdownMenu>
</template>
```

> [!TIP]
> See: #slots
> Слоты `#item`, `#item-leading`, `#item-label` и `#item-trailing` настраивают сразу все элементы.

### С переключателем в элементах

Свойство `slot` со слотом `#{{ slot }}-trailing` показывает внутри элемента [Switch](https://b24-ui.bx-shef.by/raw/docs/components/switch.md).

```vue [DropdownMenuSwitchItemsExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import Bookmark2Icon from '@bitrix24/b24icons-vue/outline/Bookmark2Icon'
import ClockWithArrowIcon from '@bitrix24/b24icons-vue/main/ClockWithArrowIcon'
import CloudDownloadIcon from '@bitrix24/b24icons-vue/outline/CloudDownloadIcon'

const showBookmarks = ref(true)
const showHistory = ref(false)
const showDownloads = ref(false)

const items = computed(() => [
  {
    label: 'Показывать закладки',
    icon: Bookmark2Icon,
    slot: 'switch' as const,
    checked: showBookmarks.value,
    onSelect(e: Event) {
      e.preventDefault()
      showBookmarks.value = !showBookmarks.value
    }
  },
  {
    label: 'Показывать историю',
    icon: ClockWithArrowIcon,
    slot: 'switch' as const,
    checked: showHistory.value,
    onSelect(e: Event) {
      e.preventDefault()
      showHistory.value = !showHistory.value
    }
  },
  {
    label: 'Показывать загрузки',
    icon: CloudDownloadIcon,
    slot: 'switch' as const,
    checked: showDownloads.value,
    onSelect(e: Event) {
      e.preventDefault()
      showDownloads.value = !showDownloads.value
    }
  }
] satisfies DropdownMenuItem[])
</script>

<template>
  <B24DropdownMenu :items="items" :content="{ align: 'start' }" :b24ui="{ content: 'w-48', viewport: 'w-48' }">
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />

    <template #switch-trailing="{ item }">
      <B24Switch :model-value="item.checked" tabindex="-1" />
    </template>
  </B24DropdownMenu>
</template>
```

### Игнорирование фильтра

Если используется пропс `filter` или поле `filter` у элементов с `children`, пропс `ignore-filter` со значением `true` отключает встроенный поиск, и вы используете свою логику поиска.

```vue [DropdownMenuIgnoreFilterExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import { refDebounced } from '@vueuse/core'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import SearchIcon from '@bitrix24/b24icons-vue/outline/SearchIcon'

const searchTerm = ref('')
const searchTermDebounced = refDebounced(searchTerm, 200)

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

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

<template>
  <B24DropdownMenu
    v-model:search-term="searchTerm"
    :items="users || []"
    :filter="{
      icon: SearchIcon,
      loading: status === 'pending'
    }"
    ignore-filter
    :content="{ align: 'start' }"
    :b24ui="{ content: 'w-48', viewport: 'w-48' }"
    @update:open="onOpen"
  >
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

> [!NOTE]
> В этом примере [`refDebounced`](https://vueuse.org/shared/refDebounced/#refdebounced) откладывает вызовы API. Загрузка отложена через `immediate: false`, поэтому пока меню не открыто, запросов нет.

### Поля фильтра

Если используется пропс `filter` или поле `filter` у элементов с `children`, пропс `filter-fields` задаёт массив полей, по которым идёт фильтрация. По умолчанию `[labelKey]`.

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

const items: DropdownMenuItem[] = [
  {
    label: 'Leanne Graham',
    description: 'Sincere@april.biz'
  },
  {
    label: 'Ervin Howell',
    description: 'Shanna@melissa.tv'
  },
  {
    label: 'Clementine Bauch',
    description: 'Nathan@yesenia.net'
  },
  {
    label: 'Patricia Lebsack',
    description: 'Julianne.OConner@kory.org'
  },
  {
    label: 'Chelsey Dietrich',
    description: 'Lucio_Hettinger@annie.me'
  }
]
</script>

<template>
  <B24DropdownMenu
    :items="items"
    filter
    :filter-fields="['label', 'description']"
    :content="{ align: 'start' }"
    :b24ui="{ content: 'w-64', viewport: 'w-64' }"
  >
    <B24Button label="Открыть" :icon="HamburgerMenuIcon" />
  </B24DropdownMenu>
</template>
```

### Ширина содержимого по триггеру

Чтобы растянуть содержимое на всю ширину кнопки, добавьте класс `w-(--reka-dropdown-menu-trigger-width)` в `b24ui.content`, а классы `min-w-(--reka-dropdown-menu-trigger-width) w-(--reka-dropdown-menu-trigger-width)` — в слот `b24ui.viewport`.

```vue [DropdownMenuContentWidthExample.vue]
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import HamburgerMenuIcon from '@bitrix24/b24icons-vue/outline/HamburgerMenuIcon'
import OpenedEyeIcon from '@bitrix24/b24icons-vue/main/OpenedEyeIcon'
import TrashBinIcon from '@bitrix24/b24icons-vue/main/TrashBinIcon'
import CopyPlatesIcon from '@bitrix24/b24icons-vue/actions/CopyPlatesIcon'
import PencilDrawIcon from '@bitrix24/b24icons-vue/actions/PencilDrawIcon'

const items: DropdownMenuItem[][] = [
  [
    {
      label: 'Просмотр',
      icon: OpenedEyeIcon
    },
    {
      label: 'Копировать',
      icon: CopyPlatesIcon
    },
    {
      label: 'Изменить',
      icon: PencilDrawIcon
    }
  ],
  [
    {
      label: 'Удалить',
      color: 'air-primary-alert' as const,
      icon: TrashBinIcon
    }
  ]
]
</script>

<template>
  <B24DropdownMenu :items="items" :b24ui="{ content: 'w-(--reka-dropdown-menu-trigger-width)', viewport: 'min-w-(--reka-dropdown-menu-trigger-width) w-(--reka-dropdown-menu-trigger-width)' }">
    <B24Button
      label="Открыть"
      class="w-46"
      block
      :icon="HamburgerMenuIcon"
    />
  </B24DropdownMenu>
</template>
```

### Извлечение сочетаний клавиш

Утилита [extractShortcuts](https://b24-ui.bx-shef.by/raw/docs/composables/extract-shortcuts.md) автоматически определяет сочетания клавиш из элементов меню со свойством `kbds`. Она обходит меню рекурсивно и возвращает объект, совместимый с [defineShortcuts](https://b24-ui.bx-shef.by/raw/docs/composables/define-shortcuts.md).

```vue
<script setup lang="ts">
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'

const items: DropdownMenuItem[] = [{
  label: 'Invite users',
  children: [{
    label: 'Invite by email',
    kbds: ['meta', 'e'],
    onSelect() {
      console.log('Invite by email clicked')
    }
  }, {
    label: 'Invite by link',
    kbds: ['meta', 'i'],
    onSelect() {
      console.log('Invite by link clicked')
    }
  }]
}, {
  label: 'New team',
  kbds: ['meta', 'n'],
  onSelect() {
    console.log('New team clicked')
  }
}]

defineShortcuts(extractShortcuts(items))
</script>
```

> [!NOTE]
> В этом примере сочетания <kbd value="meta">
> </kbd>
> <kbd value="E" className="ms-px">
> </kbd>
> , <kbd value="meta">
> </kbd>
> <kbd value="I" className="ms-px">
> </kbd>
> и <kbd value="meta">
> </kbd>
> <kbd value="N" className="ms-px">
> </kbd>
> вызывают функцию `select` соответствующего элемента.

## API

### Пропсы

```ts
/**
 * Props for the DropdownMenu component
 */
interface DropdownMenuProps {
  items?: T | undefined;
  /**
   * The icon displayed when an item is checked.
   * @default icons.check
   */
  checkedIcon?: (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;
  /**
   * The icon displayed when the item is an external link.
   * Set to `false` to hide the external icon.
   * @default true
   */
  externalIcon?: boolean | IconComponent | undefined;
  /**
   * The content of the menu.
   * @default { side: 'bottom', sideOffset: 8, collisionPadding: 8 }
   */
  content?: Omit<DropdownMenuContentProps, "as" | "asChild" | "forceMount"> & Partial<EmitsToProps<DropdownMenuContentEmits>> | undefined;
  /**
   * Display an arrow alongside the menu.
   * @default false
   */
  arrow?: boolean | Omit<DropdownMenuArrowProps, "as" | "asChild"> | undefined;
  /**
   * Render the menu in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * The key used to get the label from the item.
   * @default 'label'
   */
  labelKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * The key used to get the description from the item.
   * @default 'description'
   */
  descriptionKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * Whether to display a filter input or not.
   * Can be an object to pass additional props to the input.
   * `{ placeholder: 'Search...', noBorder: true }`
   * @default false
   */
  filter?: boolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue"> | undefined;
  /**
   * The fields to filter by.
   * @default [labelKey]
   */
  filterFields?: string[] | undefined;
  /**
   * When `true`, items will not be filtered which is useful for custom filtering.
   * @default false
   */
  ignoreFilter?: boolean | undefined;
  /**
   * @default false
   */
  disabled?: boolean | undefined;
  b24ui?: { content?: SlotClass; input?: SlotClass; empty?: SlotClass; viewport?: SlotClass; arrow?: SlotClass; group?: SlotClass; label?: SlotClass; separator?: SlotClass; item?: SlotClass; itemLeadingIcon?: SlotClass; itemLeadingAvatar?: SlotClass; itemLeadingAvatarSize?: SlotClass; itemTrailing?: SlotClass; itemTrailingIcon?: SlotClass; itemTrailingKbds?: SlotClass; itemWrapper?: SlotClass; itemTrailingKbdsSize?: SlotClass; itemLabel?: SlotClass; itemDescription?: SlotClass; itemLabelExternalIcon?: SlotClass; } | undefined;
  /**
   * The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state.
   */
  defaultOpen?: boolean | undefined;
  /**
   * The controlled open state of the menu. Can be used as `v-model:open`.
   */
  open?: boolean | undefined;
  /**
   * The modality of the dropdown menu.
   * 
   * When set to `true`, interaction with outside elements will be disabled and only menu content will be visible to screen readers.
   * @default true
   */
  modal?: boolean | undefined;
  /**
   * @default ''
   */
  searchTerm?: string | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the DropdownMenu component
 */
interface DropdownMenuSlots {
  default(): any;
  item(): any;
  item-leading(): any;
  item-label(): any;
  item-description(): any;
  item-trailing(): any;
  empty(): any;
  content-top(): any;
  content-bottom(): any;
}
```

### События

```ts
/**
 * Emitted events for the DropdownMenu component
 */
interface DropdownMenuEmits {
  update:open: (payload: [payload: boolean]) => void;
  update:searchTerm: (payload: [value: string]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    dropdownMenu: {
      slots: {
        content: 'base-mode flex flex-col max-h-[min(var(--max-height-popup-menu),var(--reka-dropdown-menu-content-available-height,var(--max-height-popup-menu)))] bg-(--ui-color-bg-content-primary) shadow-(--popup-window-box-shadow) rounded-(--ui-border-radius-xl) will-change-[opacity] motion-safe:data-[state=open]:animate-[scale-in_100ms_var(--ease-out)] motion-safe:data-[state=closed]:animate-[scale-out_100ms_var(--ease-out)] origin-(--reka-dropdown-menu-content-transform-origin) font-[family-name:var(--ui-font-family-primary)] relative isolate px-0 py-(--menu-popup-padding) bitrix-mobile:py-0! pointer-events-auto',
        input: 'border-b border-default w-full',
        empty: 'px-4.5 pt-4 pb-2 select-none outline-none whitespace-nowrap text-center text-(length:--popup-window-delimiter-font-size)/(--ui-font-line-height-lg) text-legend font-(--ui-font-weight-normal)',
        viewport: 'relative w-full min-w-48 flex-1 overflow-x-hidden overflow-y-auto scrollbar-thin',
        arrow: 'fill-(--ui-color-bg-content-primary)',
        group: 'grid',
        label: 'w-full h-(--popup-window-delimiter-section-height) bitrix-mobile:h-[27px] px-4.5 mt-(--menu-item-block-stack-space) bitrix-mobile:pe-0 bitrix-mobile:mt-0 bitrix-mobile:-mb-[12px] flex flex-row rtl:flex-row-reverse items-center select-none outline-none whitespace-nowrap text-start text-(length:--ui-size-sm) text-(--ui-color-base-3) bitrix-mobile:[&_[data-slot=itemLabel]]:text-(--ui-color-base-5) font-(--ui-font-weight-normal) after:ms-2 after:block after:flex-1 after:min-w-3 after:h-px after:bg-(--ui-color-divider-vibrant-default)',
        separator: 'bg-(--ui-color-divider-vibrant-default) my-2 mx-4.5 h-px bitrix-mobile:my-0 bitrix-mobile:mx-0 bitrix-mobile:h-1.5',
        item: 'group w-full h-9 bitrix-mobile:h-10.5 px-4.5 mt-(--menu-item-block-stack-space) bitrix-mobile:mt-0 relative flex flex-row rtl:flex-row-reverse items-center gap-2 select-none outline-none whitespace-nowrap cursor-pointer data-disabled:cursor-not-allowed data-disabled:opacity-30 text-start text-(length:--ui-font-size-md) text-(--ui-color-base-1) hover:text-(--ui-color-base-1) data-highlighted:text-(--ui-color-base-1) data-[state=open]:text-(--ui-color-base-1) hover:bg-(--ui-color-base-black-fixed)/3 dark:hover:bg-(--ui-color-base-black-fixed) active:bg-(--ui-color-base-black-fixed)/6 dark:active:bg-(--ui-color-base-black-fixed) data-highlighted:not-active:bg-(--ui-color-base-black-fixed)/3 dark:data-highlighted:not-active:bg-(--ui-color-base-black-fixed) data-[state=open]:bg-(--ui-color-base-black-fixed)/6 dark:data-[state=open]:bg-(--ui-color-base-black-fixed) bitrix-mobile:data-[state=open]:bg-(--ui-color-bg-state-hover-default) transition-colors bitrix-mobile:[[data-slot=item]+&]:border-t bitrix-mobile:border-t-(--ui-color-divider-vibrant-default) bitrix-mobile:data-highlighted:bg-(--ui-color-bg-state-hover-default)',
        itemLeadingIcon: 'size-[25px] shrink-0 text-(--ui-color-base-5)',
        itemLeadingAvatar: 'shrink-0 size-4 me-1',
        itemLeadingAvatarSize: '2xs',
        itemTrailing: 'ml-auto rtl:ml-0 rtl:mr-auto inline-flex gap-1.5 items-center',
        itemTrailingIcon: 'shrink-0 size-[25px] text-(--ui-color-base-5)',
        itemTrailingKbds: 'shrink-0 hidden lg:inline-flex items-center gap-0.5',
        itemWrapper: 'flex-1 flex flex-col text-start min-w-0',
        itemTrailingKbdsSize: 'md',
        itemLabel: 'max-w-60 truncate -mt-px',
        itemDescription: 'max-w-60 truncate -mt-[6px] text-description text-(length:--ui-font-size-sm)',
        itemLabelExternalIcon: 'inline-block size-[25px] text-(--ui-color-base-5)'
      },
      variants: {
        color: {
          'air-primary': {
            item: 'style-filled'
          },
          'air-primary-success': {
            item: 'style-filled-success'
          },
          'air-primary-alert': {
            item: 'style-filled-alert'
          },
          'air-primary-copilot': {
            item: 'style-filled-copilot'
          },
          'air-primary-warning': {
            item: 'style-filled-warning'
          },
          default: {
            item: 'style-old-default'
          },
          danger: {
            item: 'style-old-danger'
          },
          success: {
            item: 'style-old-success'
          },
          warning: {
            item: 'style-old-warning'
          },
          primary: {
            item: 'style-old-primary'
          },
          secondary: {
            item: 'style-old-secondary'
          },
          collab: {
            item: 'style-old-collab'
          },
          ai: {
            item: 'style-old-ai'
          }
        },
        active: {
          true: {
            item: '',
            itemLeadingIcon: 'text-(--ui-color-accent-main-primary) hover:text-(--ui-color-accent-main-primary) group-data-[state=open]:text-(--ui-color-accent-main-primary)'
          },
          false: {}
        },
        loading: {
          true: {
            itemLeadingIcon: 'animate-spin'
          }
        }
      },
      compoundVariants: [
        {
          color: [
            'air-primary',
            'air-primary-success',
            'air-primary-alert',
            'air-primary-copilot',
            'air-primary-warning'
          ],
          active: false,
          class: {
            item: 'text-(--b24ui-background) data-highlighted:text-(--b24ui-background-hover) data-[state=open]:text-(--b24ui-background-hover)',
            itemLeadingIcon: 'text-(--b24ui-background)'
          }
        },
        {
          color: [
            'air-primary',
            'air-primary-success',
            'air-primary-alert',
            'air-primary-copilot',
            'air-primary-warning'
          ],
          active: true,
          class: {
            item: 'text-(--b24ui-background-active)',
            itemLeadingIcon: 'text-(--b24ui-background-active) group-data-[state=open]:text-(--b24ui-background-active)'
          }
        },
        {
          color: 'default',
          active: false,
          class: ''
        },
        {
          color: 'default',
          active: true,
          class: ''
        },
        {
          color: [
            'danger',
            'success',
            'warning',
            'primary',
            'secondary',
            'collab',
            'ai'
          ],
          active: false,
          class: {
            item: 'text-(--b24ui-background-active) data-highlighted:text-(--b24ui-background-hover) data-[state=open]:text-(--b24ui-background-hover)',
            itemLeadingIcon: 'text-(--b24ui-icon)'
          }
        },
        {
          color: [
            'danger',
            'success',
            'warning',
            'primary',
            'secondary',
            'collab',
            'ai'
          ],
          active: true,
          class: {
            item: 'text-(--b24ui-background-active)',
            itemLeadingIcon: 'text-(--b24ui-background-active) group-data-[state=open]:text-(--b24ui-background-active)'
          }
        }
      ],
      defaultVariants: {}
    }
  }
})
```

## Sitemap

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