---
title: "CheckboxGroup"
description: "Список с множественным выбором на кнопочных элементах."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/checkbox-group"
---
# CheckboxGroup

> Список с множественным выбором на кнопочных элементах.

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

Значением CheckboxGroup управляет директива `v-model`, а если управлять состоянием не нужно, начальное значение задаёт пропс `default-value`.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
const value = ref([
  'Системная'
])
</script>

<template>
  <B24CheckboxGroup v-model="value" :items="items" />
</template>
```

### Элементы

Пропс `items` — массив строк или чисел:

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
const value = ref([
  'Системная'
])
</script>

<template>
  <B24CheckboxGroup v-model="value" :items="items" />
</template>
```

Можно передать и массив объектов со свойствами:

- `label?: string`
- `description?: string`
- [`value?: string`](#value-key)
- `disabled?: boolean`
- [`icon?: IconComponent`](#indicator)
- `class?: any`
- `b24ui?: { item?: ClassNameValue, container?: ClassNameValue, base?: ClassNameValue, 'indicator'?: ClassNameValue, wrapper?: ClassNameValue, label?: ClassNameValue, description?: ClassNameValue }`

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

const items = ref<CheckboxGroupItem[]>([
  {
    label: 'Системная',
    description: 'Это первый вариант.',
    value: 'system'
  },
  {
    label: 'Светлая',
    description: 'Это второй вариант.',
    value: 'light'
  },
  {
    label: 'Тёмная',
    description: 'Это третий вариант.',
    value: 'dark'
  }
])
const value = ref([
  'system'
])
</script>

<template>
  <B24CheckboxGroup v-model="value" :items="items" />
</template>
```

> [!CAUTION]
> Если элементы — объекты, в `v-model` или `default-value` указывайте свойство `value` объекта.

### Ключ значения

Свойство, из которого берётся значение, меняет пропс `value-key`. По умолчанию — `value`.

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

const items = ref<CheckboxGroupItem[]>([
  {
    label: 'Системная',
    description: 'Это первый вариант.',
    id: 'system'
  },
  {
    label: 'Светлая',
    description: 'Это второй вариант.',
    id: 'light'
  },
  {
    label: 'Тёмная',
    description: 'Это третий вариант.',
    id: 'dark'
  }
])
const value = ref([
  'light'
])
</script>

<template>
  <B24CheckboxGroup v-model="value" value-key="id" :items="items" />
</template>
```

### Легенда

Пропс `legend` задаёт легенду CheckboxGroup.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup legend="Тема" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

### Цвет

Пропс `color` меняет цвет CheckboxGroup.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup color="air-primary-copilot" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

### Вариант

Пропс `variant` меняет вариант CheckboxGroup.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup color="air-primary-copilot" variant="card" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

### Размер

Пропс `size` меняет размер CheckboxGroup.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup size="lg" variant="list" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

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

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

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup orientation="horizontal" variant="list" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

### Индикатор

Пропс `indicator` меняет положение индикатора или скрывает его. По умолчанию — `start`.

> [!NOTE]
> Пока индикатор виден, `icon` элемента заменяет галочку, а при `hidden` показывается над подписью.

```vue [CheckboxGroupIconExample.vue]
<script setup lang="ts">
import type { CheckboxGroupItem } from '@bxshefby/b24ui-nuxt'
import ThemeIcon from '@bitrix24/b24icons-vue/outline/ThemeIcon'
import SunIcon from '@bitrix24/b24icons-vue/outline/SunIcon'
import MoonIcon from '@bitrix24/b24icons-vue/outline/MoonIcon'

const items: CheckboxGroupItem[] = [
  { label: 'Системная', value: 'system', icon: ThemeIcon, class: 'w-24' },
  { label: 'Светлая', value: 'light', icon: SunIcon, class: 'w-24' },
  { label: 'Тёмная', value: 'dark', icon: MoonIcon, class: 'w-24' }
]
</script>

<template>
  <B24CheckboxGroup
    :items="items"
    :default-value="['system']"
    indicator="hidden"
    orientation="horizontal"
    variant="table"
  />
</template>
```

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup indicator="end" variant="card" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

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

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

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup disabled variant="list" :default-value="{'0':'Системная'}" :items="items" />
</template>
```

### Максимум `2.15+`

Пропс `max` ограничивает число отмечаемых элементов. Когда предел достигнут, остальные элементы отметить нельзя.

```vue
<script setup lang="ts">
const items = ref([
  'Системная',
  'Светлая',
  'Тёмная'
])
</script>

<template>
  <B24CheckboxGroup :max="2" :default-value="{'0':'Системная','1':'Светлая'}" :items="items" />
</template>
```

## Примеры

### Раскладка настроек

Вариант `card` вместе со слотом `#label` даёт выбор в стиле настроек: у каждого варианта есть заголовок, описание, ссылка «Learn more» и картинка предпросмотра. Слот подписи отрисовывается внутри `<span>`, поэтому подойдёт любая раскладка из фразового содержимого (flex, ссылка, изображение).

```vue [CheckboxGroupSettingsExample.vue]
<script setup lang="ts">
type CapabilityItem = {
  value: string
  title: string
  text: string
  href: string
}

const value = ref<string[]>(['columns'])

const items: CapabilityItem[] = [
  {
    value: 'columns',
    title: 'В колонках',
    text: 'Выберите для ресурсов, которые всегда должны быть на виду у менеджера. Это основные ресурсы, вокруг которых строится расписание.',
    href: 'https://helpdesk.bitrix24.com/'
  },
  {
    value: 'list',
    title: 'В дополнительном списке',
    text: 'Выберите для ресурсов, которые бронируются только вместе с основным. Например, если основной ресурс — специалисты, оборудование попадает в дополнительный список.',
    href: 'https://helpdesk.bitrix24.com/'
  }
]
</script>

<template>
  <B24CheckboxGroup
    v-model="value"
    variant="card"
    size="md"
    :items="items"
    class="w-full max-w-2xl"
  >
    <template #label="{ item }">
      <span class="flex gap-3 items-start w-full">
        <span class="flex-1 min-w-0 flex flex-col gap-1">
          <span class="text-(length:--ui-font-size-md) font-(--ui-font-weight-medium)">
            {{ item.title }}
          </span>
          <span class="text-(length:--ui-font-size-sm) text-description font-(--ui-font-weight-regular)">
            {{ item.text }}
          </span>
          <B24Link
            :to="item.href"
            target="_blank"
            class="self-start mt-1 text-(length:--ui-font-size-sm)"
            @click.stop
          >
            Подробнее
          </B24Link>
        </span>
        <Placeholder class="hidden sm:flex shrink-0 w-[120px] h-[72px] text-(length:--ui-font-size-xs) text-description">
          Предпросмотр
        </Placeholder>
      </span>
    </template>
  </B24CheckboxGroup>
</template>
```

> Prompt: Собрать расширенный выбор настроек на карточках с чекбоксами (предпросмотр, описание, ссылка).
> Соберите выбор настроек с несколькими переключателями на `B24CheckboxGroup` с `variant="card"`. У каждого варианта — заголовок, многострочное описание, встроенная ссылка «Learn more» и картинка предпросмотра справа; всё раскладывается через слот `#label`. Включить можно сразу несколько вариантов, поэтому `v-model` привязан к массиву.
> Прежде чем генерировать код, спросите недостающие сведения, не угадывайте:
> - сколько возможностей и какими должны быть их `value`, `title` и описание;
> - какой адрес у каждой ссылки «Learn more» (один на всех или у каждого свой);
> - откуда берётся предпросмотр: настоящая картинка, `<Placeholder>` до готовности графики или его нет вовсе;
> - нужно ли сохранять выбор (куда привязан `v-model`: локальный `ref<string[]>`, хранилище Pinia, query-параметр, сервер);
> - какие `size` (`sm` / `md` / `lg`) и токен `color` подходят странице;
> - находится ли выбор внутри `B24Form` (тогда его нужно обернуть в `B24FormField` с подписью);
> - есть ли взаимоисключающие сочетания: если да, логика живёт в родителе (например, `watch`, который убирает несовместимые значения), а не в разметке.
> Требования после подтверждения деталей:
> - Объявите локальный `interface` для формы элемента (`value`, `title`, `text`, `href`, необязательный `preview`) и типизируйте им массив. `CheckboxGroupItem[]` не используйте: он расширяет пользовательские поля до `any`
> - Внутри слота `#label` используйте только обёртки `<span>` (без `<div>` и `<p>`: в варианте `card` слот отрисовывается как `<span>`)
> - Применяйте семантические утилиты (`text-description`, `text-(length:--ui-font-size-md)` и т. п.), а не «сырые» цвета палитры Tailwind
> - Скрывайте предпросмотр ниже контрольной точки `sm` (`hidden sm:flex`)
> - Добавьте `@click.stop` встроенному `B24Link`, чтобы щелчок по ссылке не переключал чекбокс
> - Если `item.href` может прийти из ненадёжного источника, проверьте его перед привязкой (отклоняйте `javascript:`, `data:` и адреса открытого редиректа)

> [!TIP]
> Чтобы щелчок по встроенной ссылке не переключал чекбокс, добавьте ей `@click.stop`.

> [!NOTE]
> Тот же приём работает и для выбора одного варианта — см. [RadioGroup → Раскладка настроек](https://b24-ui.bx-shef.by/raw/docs/components/radio-group.md#settings-layout). Для сеток «иконка + описание» (без картинки предпросмотра) используйте [`B24PageCardGroup`](https://b24-ui.bx-shef.by/raw/docs/components/page-card-group.md).

## API

### Пропсы

```ts
/**
 * Props for the CheckboxGroup component
 */
interface CheckboxGroupProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  legend?: string | undefined;
  /**
   * When `items` is an array of objects, select the field to use as the value.
   * @default 'value'
   */
  valueKey?: VK | undefined;
  /**
   * When `items` is an array of objects, select the field to use as the label.
   * @default 'label'
   */
  labelKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  /**
   * When `items` is an array of objects, select the field to use as the description.
   * @default 'description'
   */
  descriptionKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | undefined;
  items?: T | undefined;
  /**
   * The controlled value of the CheckboxGroup. Can be bind as `v-model`.
   */
  modelValue?: GetItemValue<T, VK, undefined, NestedItem<T>>[] | undefined;
  /**
   * The value of the CheckboxGroup when initially rendered. Use when you do not need to control the state of the CheckboxGroup.
   */
  defaultValue?: GetItemValue<T, VK, undefined, NestedItem<T>>[] | undefined;
  /**
   * @default 'md'
   */
  size?: "xs" | "sm" | "md" | "lg" | undefined;
  /**
   * @default 'list'
   */
  variant?: "card" | "list" | "table" | undefined;
  /**
   * The orientation the checkbox buttons are laid out.
   * @default 'vertical'
   */
  orientation?: "horizontal" | "vertical" | undefined;
  b24ui?: { root?: SlotClass; fieldset?: SlotClass; legend?: SlotClass; item?: SlotClass; } & { root?: SlotClass; base?: SlotClass; indicator?: SlotClass; container?: SlotClass; icon?: SlotClass; wrapper?: SlotClass; label?: SlotClass; description?: SlotClass; } | undefined;
  /**
   * When `true`, prevents the user from interacting with the checkboxes
   */
  disabled?: boolean | undefined;
  /**
   * Whether keyboard navigation should loop around
   * @default false
   */
  loop?: boolean | undefined;
  /**
   * The maximum number of values that can be selected. Once reached, the unchecked
   * checkboxes get `aria-disabled` but stay focusable, so consider telling users
   * about the limit. Style them with `[aria-disabled="true"]`.
   */
  max?: null | number | undefined;
  /**
   * The name of the field. Submitted with its owning form as part of a name/value pair.
   */
  name?: string | undefined;
  /**
   * When `true`, indicates that the user must set the value before the owning form can be submitted.
   */
  required?: boolean | undefined;
  /**
   * The icon displayed when checked, or above the label when `indicator` is `hidden`.
   * @default icons.check
   */
  icon?: (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;
  /**
   * @default 'air-primary'
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-warning" | "air-primary-copilot";
  /**
   * Highlight the ring color like a focus state.
   */
  highlight?: boolean | undefined;
  /**
   * Position of the indicator.
   * @default 'start'
   */
  indicator?: "start" | "end" | "hidden" | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the CheckboxGroup component
 */
interface CheckboxGroupSlots {
  legend(): any;
  label(): any;
  description(): any;
}
```

### События

```ts
/**
 * Emitted events for the CheckboxGroup component
 */
interface CheckboxGroupEmits {
  update:modelValue: (payload: [value: GetItemValue<T, VK, undefined, NestedItem<T>>[]]) => void;
  change: (payload: [event: Event]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    checkboxGroup: {
      slots: {
        root: 'relative',
        fieldset: 'flex gap-x-2',
        legend: 'mb-1.5 block text-label',
        item: ''
      },
      variants: {
        orientation: {
          horizontal: {
            fieldset: 'flex-row'
          },
          vertical: {
            fieldset: 'flex-col'
          }
        },
        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'
          }
        },
        variant: {
          list: {
            fieldset: 'flex-wrap'
          },
          card: {
            fieldset: 'flex-wrap',
            item: 'cursor-pointer items-start border border-(--ui-color-design-outline-na-stroke) bg-(--ui-color-design-outline-na-bg) has-data-[state=checked]:border-(--b24ui-border-color)'
          },
          table: {
            item: 'cursor-pointer has-aria-disabled:cursor-not-allowed border border-(--ui-color-design-outline-na-stroke) bg-(--ui-color-design-outline-na-bg) has-data-[state=checked]:bg-(--b24ui-background)/24 has-data-[state=checked]:border-(--b24ui-border-color) has-data-[state=checked]:text-(--b24ui-color) has-data-[state=checked]:z-[1]'
          }
        },
        size: {
          xs: {
            fieldset: 'gap-x-[12px] gap-y-[4px]',
            legend: 'text-(length:--ui-font-size-xs)'
          },
          sm: {
            fieldset: 'gap-x-[14px] gap-y-[6px]',
            legend: 'text-(length:--ui-font-size-xs)'
          },
          md: {
            fieldset: 'gap-x-[16px] gap-y-2',
            legend: 'text-(length:--ui-font-size-sm)'
          },
          lg: {
            fieldset: 'gap-x-[16px] gap-y-2',
            legend: 'text-(length:--ui-font-size-sm)'
          }
        },
        disabled: {
          true: {}
        },
        required: {
          true: {
            label: "after:content-['*'] after:ms-0.5 after:text-(--ui-color-accent-main-alert)"
          }
        }
      },
      compoundVariants: [
        {
          size: 'xs',
          variant: 'card',
          class: {
            item: 'px-[13px] py-[7px] rounded-(--ui-border-radius-xs)'
          }
        },
        {
          size: 'sm',
          variant: 'card',
          class: {
            item: 'px-[13px] py-[9px] rounded-(--ui-border-radius-sm)'
          }
        },
        {
          size: 'md',
          variant: 'card',
          class: {
            item: 'px-[17px] py-[10px] rounded-(--ui-border-radius-md)'
          }
        },
        {
          size: 'lg',
          variant: 'card',
          class: {
            item: 'px-[23px] py-[12px] rounded-(--ui-border-radius-md)'
          }
        },
        {
          size: 'xs',
          variant: 'table',
          class: {
            item: 'px-[13px] py-[7px]'
          }
        },
        {
          size: 'sm',
          variant: 'table',
          class: {
            item: 'px-[13px] py-[9px]'
          }
        },
        {
          size: 'md',
          variant: 'table',
          class: {
            item: 'px-[17px] py-[10px]'
          }
        },
        {
          size: 'lg',
          variant: 'table',
          class: {
            item: 'px-[23px] py-[12px]'
          }
        },
        {
          size: 'xs',
          variant: 'table',
          orientation: 'horizontal',
          class: {
            item: 'first-of-type:rounded-s-(--ui-border-radius-xs) last-of-type:rounded-e-(--ui-border-radius-xs)',
            fieldset: 'gap-0 -space-x-px'
          }
        },
        {
          size: 'xs',
          variant: 'table',
          orientation: 'vertical',
          class: {
            item: 'first-of-type:rounded-t-(--ui-border-radius-xs) last-of-type:rounded-b-(--ui-border-radius-xs)',
            fieldset: 'gap-0 -space-y-px'
          }
        },
        {
          size: 'sm',
          variant: 'table',
          orientation: 'horizontal',
          class: {
            item: 'first-of-type:rounded-s-(--ui-border-radius-sm) last-of-type:rounded-e-(--ui-border-radius-sm)',
            fieldset: 'gap-0 -space-x-px'
          }
        },
        {
          size: 'sm',
          variant: 'table',
          orientation: 'vertical',
          class: {
            item: 'first-of-type:rounded-t-(--ui-border-radius-sm) last-of-type:rounded-b-(--ui-border-radius-sm)',
            fieldset: 'gap-0 -space-y-px'
          }
        },
        {
          size: [
            'lg',
            'md'
          ],
          variant: 'table',
          orientation: 'horizontal',
          class: {
            item: 'first-of-type:rounded-s-(--ui-border-radius-md) last-of-type:rounded-e-(--ui-border-radius-md)',
            fieldset: 'gap-0 -space-x-px'
          }
        },
        {
          size: [
            'lg',
            'md'
          ],
          variant: 'table',
          orientation: 'vertical',
          class: {
            item: 'first-of-type:rounded-t-(--ui-border-radius-md) last-of-type:rounded-b-(--ui-border-radius-md)',
            fieldset: 'gap-0 -space-y-px'
          }
        },
        {
          variant: 'table',
          disabled: true,
          class: {
            item: 'cursor-not-allowed'
          }
        }
      ],
      defaultVariants: {
        size: 'md',
        variant: 'list',
        color: 'air-primary'
      }
    }
  }
})
```

## Sitemap

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