---
title: "ToggleGroup"
description: "Набор кнопок, каждую из которых можно нажать и отжать."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/toggle-group"
---
# ToggleGroup

> Набор кнопок, каждую из которых можно нажать и отжать.

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

Директива `v-model` управляет нажатыми элементами ToggleGroup.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
const value = ref('day')
</script>

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

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

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup default-value="week" :items="items" />
</template>
```

### Элементы

Пропс `items` — массив объектов. Они принимают пропсы [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md), кроме пропсов ссылки, и поле `value`: по умолчанию это индекс элемента строкой, поэтому модель тоже хранит строки.

- `value?: AcceptableValue`
- `label?: string`
- `icon?: IconComponent`
- `disabled?: boolean`
- `class?: any`
- `b24ui?: ButtonProps['b24ui']`

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup default-value="week" :items="items" />
</template>
```

> [!WARNING]
> Все ключи элемента `items`, включая `href`, `to` и обработчики, попадают в кнопку. Не собирайте `items` из недоверенных данных.

### Иконки

Элементы с `icon` и без подписи требуют `aria-label`: по нему кнопку находят скринридеры.

```vue
<script setup lang="ts">
import { CalendarDate } from '@internationalized/date'
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
import type { ToggleGroupItem } from '@bxshefby/b24ui-nuxt'

const items = ref<ToggleGroupItem[]>([
  {
    value: 'day',
    icon: RocketIcon,
    'aria-label': 'День'
  },
  {
    value: 'week',
    icon: 'RocketIcon',
    'aria-label': 'Неделя'
  },
  {
    value: 'month',
    icon: 'RocketIcon',
    'aria-label': 'Месяц'
  }
])
</script>

<template>
  <B24ToggleGroup default-value="day" :items="items" />
</template>
```

### Несколько значений

Значение `multiple` в пропсе `type` разрешает нажимать сразу несколько элементов. Модель тогда — массив.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'Жирный',
    value: 'bold'
  },
  {
    label: 'Курсив',
    value: 'italic'
  },
  {
    label: 'Подчёркнутый',
    value: 'underline'
  }
])
</script>

<template>
  <B24ToggleGroup type="multiple" :default-value="{'0':'bold','1':'italic'}" :items="items" />
</template>
```

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

Пропс `orientation` меняет направление раскладки. По умолчанию `horizontal`.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup orientation="vertical" default-value="week" :items="items" />
</template>
```

### Соединение

Пропс `attached` соединяет элементы в одну группу, как в [FieldGroup](https://b24-ui.bx-shef.by/raw/docs/components/field-group.md).

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup attached default-value="week" :items="items" />
</template>
```

> [!WARNING]
> Крайние кнопки всегда скругляются по `--ui-btn-radius`: пропс `rounded` у элемента на них не действует. Если в группе есть и кнопки, и ссылки (`to` превращает элемент в `<a>`), скругление получится неверным: первая и последняя кнопки определяются отдельно для каждого тега.

### Цвет

Пропс `color` задаёт цвет неактивных элементов. По умолчанию `air-secondary-no-accent`.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup color="air-tertiary-no-accent" default-value="week" :items="items" />
</template>
```

### Цвет нажатого

Пропс `active-color` задаёт цвет нажатых элементов. По умолчанию `air-primary`.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup active-color="air-primary-success" default-value="week" :items="items" />
</template>
```

### Размер

Пропс `size` меняет размер элементов.

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup size="xl" default-value="week" :items="items" />
</template>
```

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

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

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

const items = ref<ToggleGroupItem[]>([
  {
    label: 'День',
    value: 'day'
  },
  {
    label: 'Неделя',
    value: 'week'
  },
  {
    label: 'Месяц',
    value: 'month'
  }
])
</script>

<template>
  <B24ToggleGroup disabled default-value="week" :items="items" />
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the ToggleGroup component
 */
interface ToggleGroupProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  items?: T[] | undefined;
  /**
   * The color of the items when not pressed.
   * @default 'air-secondary-no-accent'
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost" | "link";
  /**
   * The color of the pressed items.
   * @default 'air-primary'
   */
  activeColor?: "default" | "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost" | "danger" | "success" | "warning" | "primary" | "secondary" | "collab" | "ai" | "link" | undefined;
  size?: "xs" | "md" | "xss" | "sm" | "lg" | "xl" | undefined;
  /**
   * The orientation the items are laid out.
   * @default 'horizontal'
   */
  orientation?: "horizontal" | "vertical" | undefined;
  /**
   * Attach the items together, like in a FieldGroup.
   * @default false
   */
  attached?: boolean | undefined;
  /**
   * The key used to get the value from the item.
   * @default 'value'
   */
  valueKey?: keyof Extract<NestedItem<T>, object> & string | DotPathKeys<Extract<NestedItem<T>, object>> | 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;
  b24ui?: { root?: SlotClass; item?: SlotClass; } | undefined;
  /**
   * Determines whether a "single" or "multiple" items can be selected at a time.
   * 
   * This prop will overwrite the inferred type from `modelValue` and `defaultValue`.
   * @default 'single'
   */
  type?: "single" | "multiple" | undefined;
  /**
   * The controlled value of the active item(s).
   * 
   * Use this when you need to control the state of the items. Can be binded with `v-model`
   */
  modelValue?: null | string | number | bigint | Record<string, any> | AcceptableValue[] | undefined;
  /**
   * The default active value of the item(s).
   * 
   * Use when you do not need to control the state of the item(s).
   */
  defaultValue?: null | string | number | bigint | Record<string, any> | AcceptableValue[] | undefined;
  /**
   * When `true`, prevents the user from interacting with the toggle group and all its items.
   */
  disabled?: boolean | undefined;
  /**
   * When `loop` and `rovingFocus` is `true`, keyboard navigation will loop from last item to first, and vice versa.
   * @default true
   */
  loop?: boolean | undefined;
  /**
   * When `false`, navigating through the items using arrow keys will be disabled.
   * @default true
   */
  rovingFocus?: 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 ToggleGroup component
 */
interface ToggleGroupSlots {
  leading(): any;
  default(): any;
  trailing(): any;
}
```

### События

```ts
/**
 * Emitted events for the ToggleGroup component
 */
interface ToggleGroupEmits {
  change: (payload: [event: Event]) => void;
  update:modelValue: (payload: [payload: AcceptableValue | AcceptableValue[]]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    toggleGroup: {
      slots: {
        root: 'relative',
        item: ''
      },
      variants: {
        orientation: {
          horizontal: {
            root: 'inline-flex items-center gap-1'
          },
          vertical: {
            root: 'flex flex-col gap-1'
          }
        },
        attached: {
          true: {
            item: 'rounded-none data-[state=on]:z-[1] focus-visible:z-[2]'
          }
        }
      },
      compoundVariants: [
        {
          orientation: 'horizontal',
          attached: true,
          class: {
            root: 'gap-0',
            item: 'not-first-of-type:-ms-px first-of-type:rounded-s-(--ui-btn-radius) last-of-type:rounded-e-(--ui-btn-radius)'
          }
        },
        {
          orientation: 'vertical',
          attached: true,
          class: {
            root: 'gap-0',
            item: 'not-first-of-type:-mt-px first-of-type:rounded-t-(--ui-btn-radius) last-of-type:rounded-b-(--ui-btn-radius)'
          }
        }
      ],
      defaultVariants: {
        orientation: 'horizontal'
      }
    }
  }
})
```

## Sitemap

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