---
title: "RadioGroup"
description: "Набор переключателей для выбора одного варианта из нескольких."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/radio-group"
---
# RadioGroup

> Набор переключателей для выбора одного варианта из нескольких.

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

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

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

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

### Элементы

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

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

<template>
  <B24RadioGroup 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, icon?: ClassNameValue, description?: ClassNameValue }`

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

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

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

> [!CAUTION]
> При использовании объектов в директиве `v-model` или пропсе `default-value` нужно указывать свойство `value` объекта.

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

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

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

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

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

### Легенда

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

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

<template>
  <B24RadioGroup legend="Тема" default-value="Системная" :items="items" />
</template>
```

### Цвет

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

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

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

### Вариант

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

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

const items = ref<RadioGroupItem[]>([
  {
    label: 'Pro',
    value: 'pro',
    description: 'Для независимых разработчиков, фрилансеров и одиночных основателей.'
  },
  {
    label: 'Стартап',
    value: 'startup',
    description: 'Подходит небольшим командам, стартапам и агентствам.'
  },
  {
    label: 'Корпоративный',
    value: 'enterprise',
    description: 'Для крупных команд и организаций.'
  }
])
</script>

<template>
  <B24RadioGroup color="air-primary-copilot" variant="card" default-value="pro" :items="items" />
</template>
```

### Размер

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

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

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

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

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

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

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

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

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

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

```vue [RadioGroupIconExample.vue]
<script setup lang="ts">
import type { RadioGroupItem } 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: RadioGroupItem[] = [
  { 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>
  <B24RadioGroup
    :items="items"
    default-value="system"
    indicator="hidden"
    orientation="horizontal"
    variant="table"
  />
</template>
```

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

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

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

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

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

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

## Примеры

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

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

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

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

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

<template>
  <B24RadioGroup
    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>
  </B24RadioGroup>
</template>
```

> Prompt: Собрать расширенный выбор настроек на карточках с переключателями (предпросмотр, описание, ссылка).
> Соберите выбор настроек на `B24RadioGroup` с `variant="card"`. У каждого варианта — заголовок, многострочное описание, встроенная ссылка «Learn more» и картинка предпросмотра справа; всё раскладывается через слот `#label`.
> Прежде чем генерировать код, спросите недостающие сведения, не угадывайте:
> - сколько вариантов и какими должны быть их `value`, `title` и описание;
> - какой адрес у каждой ссылки «Learn more» (один на всех или у каждого свой);
> - откуда берётся предпросмотр: настоящая картинка, `<Placeholder>` до готовности графики или его нет вовсе;
> - нужно ли сохранять выбор (куда привязан `v-model`: локальный `ref`, хранилище Pinia, query-параметр, сервер);
> - какие `size` (`sm` / `md` / `lg`) и токен `color` подходят странице;
> - находится ли выбор внутри `B24Form` (тогда его нужно обернуть в `B24FormField` с подписью).
> Требования после подтверждения деталей:
> - Объявите локальный `interface` для формы элемента (`value`, `title`, `text`, `href`, необязательный `preview`) и типизируйте им массив — НЕ используйте `RadioGroupItem[]` (он расширяет пользовательские поля до `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]
> Тот же приём работает и для выбора нескольких вариантов — см. [CheckboxGroup → Раскладка настроек](https://b24-ui.bx-shef.by/raw/docs/components/checkbox-group.md#settings-layout). Для сеток «иконка + описание» (без картинки предпросмотра) используйте [`B24PageCardGroup`](https://b24-ui.bx-shef.by/raw/docs/components/page-card-group.md).

## API

### Пропсы

```ts
/**
 * Props for the RadioGroup component
 */
interface RadioGroupProps {
  /**
   * 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 RadioGroup. Can be bind as `v-model`.
   */
  modelValue?: GetItemValue<T, VK, undefined, NestedItem<T>> | undefined;
  /**
   * The value of the RadioGroup when initially rendered. Use when you do not need to control the state of the RadioGroup.
   */
  defaultValue?: GetItemValue<T, VK, undefined, NestedItem<T>> | undefined;
  /**
   * @default 'md'
   */
  size?: "xs" | "sm" | "md" | "lg" | undefined;
  /**
   * @default 'list'
   */
  variant?: "card" | "list" | "table" | 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;
  /**
   * The orientation the radio buttons are laid out.
   * @default 'vertical'
   */
  orientation?: "horizontal" | "vertical" | undefined;
  /**
   * Position of the indicator.
   * @default 'start'
   */
  indicator?: "start" | "end" | "hidden" | undefined;
  b24ui?: { root?: SlotClass; fieldset?: SlotClass; legend?: SlotClass; item?: SlotClass; icon?: SlotClass; base?: SlotClass; indicator?: SlotClass; container?: SlotClass; wrapper?: SlotClass; label?: SlotClass; description?: SlotClass; } | undefined;
  /**
   * When `true`, prevents the user from interacting with radio items.
   */
  disabled?: boolean | undefined;
  /**
   * When `true`, keyboard navigation will loop from last item to first, and vice versa.
   */
  loop?: boolean | 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;
}
```

### Слоты

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

### События

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

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    radioGroup: {
      slots: {
        root: 'relative',
        fieldset: 'flex',
        legend: 'mb-1.5 block text-label',
        item: 'flex items-start',
        icon: 'shrink-0',
        base: 'cursor-pointer rounded-(--ui-border-radius-pill) ring ring-inset ring-(--ui-color-base-5) outline-(--ui-color-background-transparent) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--b24ui-background)',
        indicator: 'flex items-center justify-center size-full rounded-(--ui-border-radius-pill) after:bg-(--b24ui-color) after:rounded-(--ui-border-radius-pill) bg-(--b24ui-background)',
        container: 'flex items-center',
        wrapper: 'font-[family-name:var(--ui-font-family-primary)] font-(--ui-font-weight-regular) w-full',
        label: 'cursor-pointer block text-label',
        description: 'text-description'
      },
      variants: {
        color: {
          'air-primary': {
            root: 'style-filled'
          },
          'air-primary-success': {
            root: 'style-filled-success'
          },
          'air-primary-alert': {
            root: 'style-filled-alert'
          },
          'air-primary-copilot': {
            root: 'style-filled-copilot'
          },
          'air-primary-warning': {
            root: 'style-filled-warning'
          },
          default: {
            root: 'style-old-default'
          },
          danger: {
            root: 'style-old-danger'
          },
          success: {
            root: 'style-old-success'
          },
          warning: {
            root: 'style-old-warning'
          },
          primary: {
            root: 'style-old-primary'
          },
          secondary: {
            root: 'style-old-secondary'
          },
          collab: {
            root: 'style-old-collab'
          },
          ai: {
            root: '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 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]'
          }
        },
        orientation: {
          horizontal: {
            fieldset: 'flex-row',
            root: 'me-2'
          },
          vertical: {
            fieldset: 'flex-col'
          }
        },
        indicator: {
          start: {
            item: 'flex-row',
            base: 'me-2'
          },
          end: {
            item: 'flex-row-reverse',
            base: 'ms-2'
          },
          hidden: {
            base: 'sr-only',
            item: 'outline-(--ui-color-background-transparent) has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-(--b24ui-background)',
            wrapper: 'flex flex-col items-center gap-1 text-center'
          }
        },
        size: {
          xs: {
            fieldset: 'gap-x-[12px] gap-y-[4px]',
            legend: 'text-(length:--ui-font-size-xs)',
            base: 'size-[12px]',
            item: 'text-(length:--ui-font-size-xs)',
            label: 'leading-[11px]',
            container: 'h-[12px]',
            indicator: 'after:size-[4px]'
          },
          sm: {
            fieldset: 'gap-x-[14px] gap-y-[6px]',
            legend: 'text-(length:--ui-font-size-xs)',
            base: 'size-[14px]',
            item: 'text-(length:--ui-font-size-sm)',
            label: 'leading-[14px]',
            container: 'h-[14px]',
            indicator: 'after:size-[6px]'
          },
          md: {
            fieldset: 'gap-x-[16px] gap-y-2',
            legend: 'text-(length:--ui-font-size-sm)',
            base: 'size-[16px]',
            item: 'text-(length:--ui-font-size-lg)',
            label: 'leading-[15px]',
            container: 'h-[16px]',
            indicator: 'after:size-[6px]'
          },
          lg: {
            fieldset: 'gap-x-[16px] gap-y-2',
            legend: 'text-(length:--ui-font-size-sm)',
            base: 'size-[20px]',
            item: 'text-(length:--ui-font-size-xl)',
            label: 'leading-4.5',
            container: 'h-[20px]',
            indicator: 'after:size-2'
          }
        },
        disabled: {
          true: {
            item: 'opacity-30',
            base: 'cursor-not-allowed',
            label: 'cursor-not-allowed',
            description: 'cursor-not-allowed'
          }
        },
        required: {
          true: {
            label: "after:content-['*'] after:ms-0.5 after:text-(--ui-color-accent-main-alert)"
          }
        },
        highlight: {
          true: {
            base: 'ring ring-inset ring-(--b24ui-border-color)'
          }
        }
      },
      compoundVariants: [
        {
          indicator: 'hidden',
          class: {
            container: 'h-auto'
          }
        },
        {
          size: 'xs',
          indicator: 'hidden',
          class: {
            icon: 'size-3'
          }
        },
        {
          size: 'sm',
          indicator: 'hidden',
          class: {
            icon: 'size-3.5'
          }
        },
        {
          size: 'md',
          indicator: 'hidden',
          class: {
            icon: 'size-4'
          }
        },
        {
          size: 'lg',
          indicator: 'hidden',
          class: {
            icon: 'size-4.5'
          }
        },
        {
          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: [
            'card',
            'table'
          ],
          disabled: true,
          class: {
            item: 'cursor-not-allowed'
          }
        }
      ],
      defaultVariants: {
        color: 'air-primary',
        size: 'md',
        variant: 'list',
        indicator: 'start'
      }
    }
  }
})
```

## Sitemap

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