v2.15.0

DropdownMenu

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

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

Поместите в слот по умолчанию DropdownMenu компонент Button или любой другой.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 — массив объектов со свойствами:

Можно передать любое свойство компонента Link: to, target и другие.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Чтобы получить отдельные группы элементов, передайте в items массив массивов.
Чтобы создать вложенное меню, элемент может содержать массив children с такими же свойствами, как у items. Вложенным меню можно управлять через свойства open, defaultOpen и content.

Содержимое

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

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

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

Поле фильтра можно настроить любым свойством компонента Input.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
Фильтр можно включить и в отдельных вложенных меню: для этого используйте поле filter у элементов с children.

Стрелка

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

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

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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 управляет отмеченным состоянием элемента.

<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>
<script setup lang="ts">
import { ref, computed } from 'vue'
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>
Чтобы состояние checked у элементов было реактивным, оберните массив items в computed.

С цветом

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

<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 показывает поле фильтра внутри вложенного меню.

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

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
В этом примере с помощью defineShortcuts DropdownMenu открывается и закрывается клавишей O.

Свой слот

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

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

  • #{{ item.slot }}
  • #{{ item.slot }}-leading
  • #{{ item.slot }}-label
  • #{{ item.slot }}-trailing
<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>
Слоты #item, #item-leading, #item-label и #item-trailing настраивают сразу все элементы.

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

Свойство slot со слотом #{{ slot }}-trailing показывает внутри элемента Switch.

<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>
<script setup lang="ts">
import { ref, computed } from 'vue'
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 отключает встроенный поиск, и вы используете свою логику поиска.

<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
В этом примере refDebounced откладывает вызовы API. Загрузка отложена через immediate: false, поэтому пока меню не открыто, запросов нет.

Поля фильтра

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

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

<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 автоматически определяет сочетания клавиш из элементов меню со свойством kbds. Она обходит меню рекурсивно и возвращает объект, совместимый с defineShortcuts.

<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>
В этом примере сочетания CtrlE, CtrlI и CtrlN вызывают функцию select соответствующего элемента.

API

Пропсы

Prop Default Type
items T
checkedIconicons.checkIconComponent

The icon displayed when an item is checked.

externalIcontrueIconComponent

The icon displayed when the item is an external link. Set to false to hide the external icon.

content{ side: 'bottom', sideOffset: 8, collisionPadding: 8 } DropdownMenuContentProps & Partial<EmitsToProps<DropdownMenuContentEmits>>

The content of the menu.

arrowfalseboolean | DropdownMenuArrowProps

Display an arrow alongside the menu.

portaltrue string | false | true | HTMLElement

Render the menu in a portal.

labelKey'label' keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>>

The key used to get the label from the item.

descriptionKey'description' keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>>

The key used to get the description from the item.

filterfalseboolean | Omit<InputProps<AcceptableValue, ModelModifiers>, "modelValue" | "defaultValue">

Whether to display a filter input or not. Can be an object to pass additional props to the input. { placeholder: 'Search...', noBorder: true }

filterFields[labelKey] string[]

The fields to filter by.

ignoreFilterfalseboolean

When true, items will not be filtered which is useful for custom filtering.

disabledfalseboolean
defaultOpenboolean

The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state.

openboolean

The controlled open state of the menu. Can be used as v-model:open.

modaltrueboolean

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.

searchTerm'' string
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; }

Слоты

Slot Type
default{ open: boolean; }
item{ item: NestedItem<T>; active: boolean; index: number; b24ui: object; }
item-leading{ item: NestedItem<T>; active: boolean; index: number; b24ui: object; }
item-label{ item: NestedItem<T>; active: boolean; index: number; }
item-description{ item: NestedItem<T>; active: boolean; index: number; }
item-trailing{ item: NestedItem<T>; active: boolean; index: number; b24ui: object; }
empty{ searchTerm: string; }
content-top{ sub: boolean; }
content-bottom{ sub: boolean; }

События

Event Type
update:open[payload: boolean]
update:searchTerm[value: string]

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/dropdown-menu.ts
export default {
  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: [],
  defaultVariants: {}
}
Some colors in compoundVariants are omitted for readability. Check out the source code on GitHub.