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

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

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

Tabs показывает список элементов в виде вкладок.

```vue [TabsExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import Shield2ContourIcon from '@bitrix24/b24icons-vue/main/Shield2ContourIcon'

const items = [
  {
    label: 'Аккаунт',
    icon: UserIcon,
    slot: 'account'
  },
  {
    label: 'Пароль',
    icon: Shield2ContourIcon,
    slot: 'password'
  }
] satisfies TabsItem[]

const state = reactive({
  name: 'System User',
  username: 'system-user',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})
</script>

<template>
  <B24Tabs :items="items">
    <template #account>
      <B24Form :state="state" class="flex flex-col gap-4">
        <B24FormField label="Имя" name="name">
          <B24Input v-model="state.name" class="w-full" />
        </B24FormField>
        <B24FormField label="Имя пользователя" name="username">
          <B24Input v-model="state.username" class="w-full" />
        </B24FormField>
      </B24Form>
    </template>

    <template #password>
      <B24Form :state="state" class="flex flex-col gap-4">
        <B24FormField label="Текущий пароль" name="current" required>
          <B24Input v-model="state.currentPassword" type="password" required class="w-full" />
        </B24FormField>
        <B24FormField label="Новый пароль" name="new" required>
          <B24Input v-model="state.newPassword" type="password" required class="w-full" />
        </B24FormField>
        <B24FormField label="Подтверждение пароля" name="confirm" required>
          <B24Input v-model="state.confirmPassword" type="password" required class="w-full" />
        </B24FormField>
      </B24Form>
    </template>
  </B24Tabs>
</template>
```

### Элементы

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

- `label?: string`
- [`icon?: IconComponent`](#usage)
- `avatar?: AvatarProps`
- `badge?: string | number | BadgeProps`
- `content?: string`
- `value?: string | number`
- `disabled?: boolean`
- [`slot?: string`](#with-custom-slot)
- `class?: any`
- `b24ui?: { trigger?: ClassNameValue, leadingIcon?: ClassNameValue, leadingAvatar?: ClassNameValue, leadingAvatarSize?: ClassNameValue, label?: ClassNameValue, trailingBadge?: ClassNameValue, trailingBadgeSize?: ClassNameValue, content?: ClassNameValue }`

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

const items = ref<TabsItem[]>([
  {
    label: 'Аккаунт',
    content: 'Это содержимое аккаунта.'
  },
  {
    label: 'Пароль',
    content: 'Это содержимое пароля.'
  }
])
</script>

<template>
  <B24Tabs :items="items" class="w-full" />
</template>
```

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

Значение `false` в пропсе `content` отрисовывает триггеры без панелей. По умолчанию `true`.

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

const items = ref<TabsItem[]>([
  {
    label: 'Аккаунт',
    content: 'Это содержимое аккаунта.'
  },
  {
    label: 'Пароль',
    content: 'Это содержимое пароля.'
  }
])
</script>

<template>
  <B24Tabs :content="false" :items="items" class="w-full" />
</template>
```

### Выгрузка содержимого

Пропс `unmount-on-hide` не даёт выгружать содержимое, когда вкладка скрыта. По умолчанию `true`.

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

const items = ref<TabsItem[]>([
  {
    label: 'Аккаунт',
    content: 'Это содержимое аккаунта.'
  },
  {
    label: 'Пароль',
    content: 'Это содержимое пароля.'
  }
])
</script>

<template>
  <B24Tabs :unmount-on-hide="false" :items="items" class="w-full" />
</template>
```

> [!NOTE]
> В DOM видно, что содержимое каждого элемента отрисовано.

### Размер

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

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

const items = ref<TabsItem[]>([
  {
    label: 'Аккаунт'
  },
  {
    label: 'Пароль'
  }
])
</script>

<template>
  <B24Tabs size="xl" :content="false" :items="items" class="w-full" />
</template>
```

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

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

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

const items = ref<TabsItem[]>([
  {
    label: 'Аккаунт'
  },
  {
    label: 'Пароль'
  }
])
</script>

<template>
  <B24Tabs orientation="vertical" :content="false" :items="items" class="w-full" />
</template>
```

## Примеры

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

Активным элементом управляют пропс `default-value` или директива `v-model` со значением `value` элемента. Если `value` не задан, берётся индекс **в виде строки**.

```vue [TabsModelValueExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import Shield2ContourIcon from '@bitrix24/b24icons-vue/main/Shield2ContourIcon'

const items: TabsItem[] = [
  {
    label: 'Аккаунт',
    icon: UserIcon
  },
  {
    label: 'Пароль',
    icon: Shield2ContourIcon
  }
]

const active = ref('0')

// Примечание: только для демонстрации, в реальном проекте так делать не стоит.
onMounted(() => {
  setInterval(() => {
    active.value = String((Number(active.value) + 1) % items.length)
  }, 2000)
})
</script>

<template>
  <B24Tabs v-model="active" :content="false" :items="items" class="w-full" />
</template>
```

> [!TIP]
> Пропс `value-key` меняет ключ, по которому элементы сопоставляются с `v-model` или `default-value`.

### С query-параметром маршрута

Активным элементом можно управлять через query-параметр URL, используя `route.query.tab` как `value` элемента.

```vue [TabsRouteQueryExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import Shield2ContourIcon from '@bitrix24/b24icons-vue/main/Shield2ContourIcon'

const route = useRoute()
const router = useRouter()

const items: TabsItem[] = [
  {
    label: 'Аккаунт',
    icon: UserIcon,
    value: 'account'
  },
  {
    label: 'Пароль',
    icon: Shield2ContourIcon,
    value: 'password'
  }
]

const active = computed({
  get() {
    return (route.query.tab as string) || 'account'
  },
  set(tab) {
    // Хеш указан здесь, чтобы страница не прокручивалась наверх
    router.push({
      path: '/b24ui/docs/components/tabs',
      query: { tab },
      hash: '#with-route-query'
    })
  }
})
</script>

<template>
  <B24Tabs v-model="active" :content="false" :items="items" class="w-full" />
</template>
```

### Со слотом content

Слот `#content` настраивает содержимое каждого элемента.

```vue [TabsContentSlotExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import Shield2ContourIcon from '@bitrix24/b24icons-vue/main/Shield2ContourIcon'

const items: TabsItem[] = [
  {
    label: 'Аккаунт',
    icon: UserIcon
  },
  {
    label: 'Пароль',
    icon: Shield2ContourIcon
  }
]
</script>

<template>
  <B24Tabs :items="items" class="w-full">
    <template #content="{ item }">
      <p>This is the {{ item.label }} tab.</p>
    </template>
  </B24Tabs>
</template>
```

### С нижней панелью вкладок

Пропс `b24ui` превращает Tabs в нижнюю панель вкладок в мобильном стиле: значки и маленькие подписи, как в YouTube или Instagram.

```vue [TabsBottomTabBarExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import HomePageIcon from '@bitrix24/b24icons-vue/main/HomePageIcon'
import ActivityIcon from '@bitrix24/b24icons-vue/main/ActivityIcon'
import SettingsIcon from '@bitrix24/b24icons-vue/main/SettingsIcon'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'

const items: TabsItem[] = [
  {
    label: 'Главная',
    icon: HomePageIcon
  },
  {
    label: 'Активность',
    icon: ActivityIcon
  },
  {
    label: 'Настройки',
    icon: SettingsIcon
  },
  {
    label: 'Профиль',
    icon: UserIcon
  }
]
</script>

<template>
  <B24Tabs
    :items="items"
    :content="false"
    :b24ui="{
      list: 'justify-around w-full',
      trigger: 'grow flex-col gap-1 py-1',
      label: 'text-[10px]/3'
    }"
    class="w-full"
  />
</template>
```

### С собственным слотом

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

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

- `#{{ item.slot }}`

```vue [TabsCustomSlotExample.vue]
<script setup lang="ts">
import type { TabsItem } from '@bxshefby/b24ui-nuxt'
import UserIcon from '@bitrix24/b24icons-vue/common-b24/UserIcon'
import Shield2ContourIcon from '@bitrix24/b24icons-vue/main/Shield2ContourIcon'

const items = [
  {
    label: 'Аккаунт',
    description: 'Здесь можно изменить данные аккаунта. Нажмите «Сохранить», когда закончите.',
    icon: UserIcon,
    slot: 'account' as const
  },
  {
    label: 'Пароль',
    description: 'Здесь можно сменить пароль. После сохранения вы выйдете из системы.',
    icon: Shield2ContourIcon,
    slot: 'password' as const
  }
] satisfies TabsItem[]

const state = reactive({
  name: 'System User',
  username: 'system-user',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})
</script>

<template>
  <B24Tabs :items="items" variant="link" :b24ui="{ trigger: 'grow' }" class="gap-4 w-full">
    <template #account="{ item }">
      <ProseP accent="less" class="mb-4">
        {{ item.description }}
      </ProseP>

      <B24Form :state="state" class="flex flex-col gap-4">
        <B24FormField label="Имя" name="name">
          <B24Input v-model="state.name" class="w-full" />
        </B24FormField>
        <B24FormField label="Имя пользователя" name="username">
          <B24Input v-model="state.username" class="w-full" />
        </B24FormField>

        <B24Button label="Сохранить изменения" type="submit" color="air-primary-success" class="self-end" />
      </B24Form>
    </template>

    <template #password="{ item }">
      <ProseP accent="less" class="mb-4">
        {{ item.description }}
      </ProseP>

      <B24Form :state="state" class="flex flex-col gap-4">
        <B24FormField label="Текущий пароль" name="current" required>
          <B24Input v-model="state.currentPassword" type="password" required class="w-full" />
        </B24FormField>
        <B24FormField label="Новый пароль" name="new" required>
          <B24Input v-model="state.newPassword" type="password" required class="w-full" />
        </B24FormField>
        <B24FormField label="Подтверждение пароля" name="confirm" required>
          <B24Input v-model="state.confirmPassword" type="password" required class="w-full" />
        </B24FormField>

        <B24Button label="Сменить пароль" type="submit" color="air-primary-success" class="self-end" />
      </B24Form>
    </template>
  </B24Tabs>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the Tabs component
 */
interface TabsProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  items?: T[] | undefined;
  /**
   * @default 'link'
   */
  variant?: "link" | undefined;
  /**
   * @default 'md'
   */
  size?: "sm" | "xs" | "md" | "xss" | "lg" | "xl" | undefined;
  /**
   * The orientation of the tabs.
   * @default 'horizontal'
   */
  orientation?: "horizontal" | "vertical" | undefined;
  /**
   * The content of the tabs, can be disabled to prevent rendering the content.
   * @default true
   */
  content?: 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; list?: SlotClass; indicator?: SlotClass; trigger?: SlotClass; leadingIcon?: SlotClass; leadingAvatar?: SlotClass; leadingAvatarSize?: SlotClass; label?: SlotClass; trailingBadge?: SlotClass; trailingBadgeSize?: SlotClass; content?: SlotClass; } | undefined;
  /**
   * The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs
   * @default '0'
   */
  defaultValue?: string | number | undefined;
  /**
   * The controlled value of the tab to activate. Can be bind as `v-model`.
   */
  modelValue?: string | number | undefined;
  /**
   * Whether a tab is activated automatically (on focus) or manually (on click).
   * @default automatic
   */
  activationMode?: "automatic" | "manual" | undefined;
  /**
   * When `true`, the element will be unmounted on closed state.
   * @default true
   */
  unmountOnHide?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Tabs component
 */
interface TabsSlots {
  leading(): any;
  default(): any;
  trailing(): any;
  content(): any;
  list-leading(): any;
  list-trailing(): any;
}
```

### События

```ts
/**
 * Emitted events for the Tabs component
 */
interface TabsEmits {
  update:modelValue: (payload: [payload: string | number]) => void;
}
```

### Доступ через ref

При обращении к компоненту через ref в шаблоне доступно:

| Имя | Тип |
| --- | --- |
| `triggersRef` | `Ref<ComponentPublicInstance[]>` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    tabs: {
      slots: {
        root: 'style-outline-accent-2 flex items-center gap-2',
        list: 'relative flex p-1 group',
        indicator: 'absolute transition-[translate,width] duration-200 motion-reduce:transition-none',
        trigger: 'group relative inline-flex items-center min-w-0 data-[state=inactive]:text-(--ui-color-design-plain-na-content) hover:data-[state=inactive]:not-disabled:text-(--ui-color-design-selection-content) font-(--ui-font-weight-medium) cursor-pointer disabled:cursor-not-allowed disabled:opacity-30 transition-colors rounded-(--ui-border-radius-md)',
        leadingIcon: 'shrink-0',
        leadingAvatar: 'shrink-0',
        leadingAvatarSize: '',
        label: '',
        trailingBadge: 'shrink-0',
        trailingBadgeSize: 'sm',
        content: 'focus:outline-none w-full'
      },
      variants: {
        variant: {
          link: {
            list: 'border-(--ui-color-divider-vibrant-accent-more)',
            indicator: 'rounded-(--ui-border-radius-pill)',
            trigger: [
              'focus:outline-none',
              "in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:content-[''] in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:absolute in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:rounded-(--ui-border-radius-pill)"
            ]
          }
        },
        orientation: {
          horizontal: {
            root: 'flex-col',
            list: 'w-full',
            indicator: 'left-0 w-(--reka-tabs-indicator-size) translate-x-(--reka-tabs-indicator-position)',
            trigger: 'justify-center'
          },
          vertical: {
            list: 'flex-col',
            indicator: 'top-0 h-(--reka-tabs-indicator-size) translate-y-(--reka-tabs-indicator-position)'
          }
        },
        size: {
          xss: {
            trigger: 'px-2 py-1 text-(length:--ui-font-size-4xs)/[normal] gap-1',
            leadingIcon: 'size-4',
            leadingAvatarSize: '3xs'
          },
          xs: {
            trigger: 'px-2 py-1 text-(length:--ui-font-size-xs)/[normal] gap-1',
            leadingIcon: 'size-4',
            leadingAvatarSize: '3xs'
          },
          sm: {
            trigger: 'px-2.5 py-1.5 text-(length:--ui-font-size-sm)/[normal] gap-1.5',
            leadingIcon: 'size-4',
            leadingAvatarSize: '3xs'
          },
          md: {
            trigger: 'px-3 py-1.5 text-(length:--ui-font-size-md)/[normal] gap-1.5',
            leadingIcon: 'size-5',
            leadingAvatarSize: '2xs'
          },
          lg: {
            trigger: 'px-3 py-2 text-(length:--ui-font-size-lg)/[normal] gap-2',
            leadingIcon: 'size-5',
            leadingAvatarSize: '2xs'
          },
          xl: {
            trigger: 'px-3 py-2 text-(length:--ui-font-size-xl)/[normal] gap-2',
            leadingIcon: 'size-6',
            leadingAvatarSize: 'xs'
          }
        }
      },
      compoundVariants: [
        {
          orientation: 'horizontal',
          variant: 'link',
          class: {
            list: 'border-b -mb-px',
            indicator: '-bottom-px h-px',
            trigger: 'in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:inset-x-0 in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:-bottom-[calc(var(--spacing)+1px)] in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:h-px'
          }
        },
        {
          orientation: 'vertical',
          variant: 'link',
          class: {
            list: 'border-s -ms-px',
            indicator: '-start-px w-px',
            trigger: 'in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:inset-y-0 in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:-start-[calc(var(--spacing)+1px)] in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:w-px'
          }
        },
        {
          variant: 'link',
          class: {
            indicator: 'bg-(--ui-color-design-selection-content)',
            trigger: [
              'focus-visible:ring-1 focus-visible:ring-inset',
              'data-[state=active]:text-(--b24ui-color)',
              'focus-visible:ring-(--ui-color-design-selection-content)',
              'in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:bg-(--ui-color-design-selection-content)'
            ]
          }
        }
      ],
      defaultVariants: {
        variant: 'link',
        size: 'md'
      }
    }
  }
})
```

## Sitemap

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