---
title: "ContentToc"
description: "Закреплённое оглавление с динамической подсветкой активного раздела."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/content-toc"
---
# ContentToc

> Закреплённое оглавление с динамической подсветкой активного раздела.

> [!WARNING]
> See: /docs/getting-started/integrations/content/
> Компонент доступен, только если установлен модуль `@nuxt/content`.

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

Пропс `links` принимает `page?.body?.toc?.links`, которое возвращается при получении страницы.

> [!NOTE]
> Подсветка текущей позиции читателя работает сама. Лежащий в её основе композабл `useScrollspy` экспортируется отдельно, если вы собираете своё оглавление: `const { activeHeadings, updateHeadings } = useScrollspy()`. После изменения контента вызывайте `updateHeadings()` с элементами заголовков, за которыми нужно следить. Используйте `activeHeadings`, а не `visibleHeadings`: он оставляет подсвеченным последний заголовок, пока читатель находится между двумя, а `visibleHeadings` в этот момент пустеет, и подсветка мигает.

```vue [ContentTocExample.vue]
<script setup lang="ts">
const route = useRoute()

const { data: page } = await useAsyncData(route.path, () => queryCollection('docs').path(route.path).first())
if (!page.value) {
  throw createError({ status: 404, statusText: 'Страница не найдена', fatal: true })
}
</script>

<template>
  <B24ContentToc :links="page?.body?.toc?.links" />
</template>
```

### Заголовок

Пропс `title` меняет заголовок оглавления.

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

const links = ref<ContentTocLink[]>([
  {
    id: 'usage',
    depth: 2,
    text: 'Использование',
    children: [
      {
        id: 'title',
        depth: 3,
        text: 'Заголовок'
      }
    ]
  },
  {
    id: 'api',
    depth: 2,
    text: 'API',
    children: [
      {
        id: 'props',
        depth: 3,
        text: 'Пропсы'
      },
      {
        id: 'slots',
        depth: 3,
        text: 'Слоты'
      }
    ]
  },
  {
    id: 'theme',
    depth: 2,
    text: 'Тема'
  }
])
</script>

<template>
  <B24ContentToc title="На этой странице" :links="links" />
</template>
```

## Примеры

### На странице

Компонент ContentToc на странице показывает оглавление:

```vue [pages/[...slug].vue]
<script setup lang="ts">
const route = useRoute()

const { data: page } = await useAsyncData(route.path, () => queryCollection('docs').path(route.path).first())
if (!page.value) {
  throw createError({ status: 404, statusText: 'Page not found', fatal: true })
}
</script>

<template>
  <template v-if="page">
    <ProseH1>{{ page.title }}</ProseH1>

    <template v-if="page?.body?.toc?.links?.length">
      <B24ContentToc :links="page.body.toc.links" />
    </template>

    <div>
      <ContentRenderer v-if="page.body" :value="page" />

      <B24Separator v-if="surround?.filter(Boolean).length" class="my-4" />

      <B24ContentSurround :surround="(surround as any)" />
    </div>
  </template>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the ContentToc component
 */
interface ContentTocProps {
  /**
   * The element or component this component should render as.
   * @default 'nav'
   */
  as?: any;
  /**
   * The icon displayed to collapse the content.
   * @default icons.chevronDown
   */
  trailingIcon?: (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;
  /**
   * The title of the table of contents.
   * @default t('contentToc.title')
   */
  title?: string | undefined;
  links?: T[] | undefined;
  b24ui?: { root?: SlotClass; container?: SlotClass; top?: SlotClass; bottom?: SlotClass; trigger?: SlotClass; title?: SlotClass; trailing?: SlotClass; trailingIcon?: SlotClass; content?: SlotClass; list?: SlotClass; listWithChildren?: SlotClass; item?: SlotClass; itemWithChildren?: SlotClass; link?: SlotClass; linkText?: SlotClass; } | undefined;
  /**
   * The open state of the collapsible when it is initially rendered. <br> Use when you do not need to control its open state.
   */
  defaultOpen?: boolean | undefined;
  /**
   * The controlled open state of the collapsible. Can be binded with `v-model`.
   */
  open?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the ContentToc component
 */
interface ContentTocSlots {
  leading(): any;
  default(): any;
  trailing(): any;
  content(): any;
  link(): any;
  top(): any;
  bottom(): any;
}
```

### События

```ts
/**
 * Emitted events for the ContentToc component
 */
interface ContentTocEmits {
  update:open: (payload: [value: boolean]) => void;
  move: (payload: [id: string]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    contentToc: {
      slots: {
        root: 'flex flex-col lg:overflow-hidden',
        container: 'border-dashed border-b-(length:--ui-border-width-thick) border-(--ui-color-divider-vibrant-default) lg:border-0 flex flex-col lg:min-h-0',
        top: 'lg:shrink-0',
        bottom: 'hidden lg:flex lg:flex-col lg:shrink-0 gap-[24px]',
        trigger: 'group pb-[12px] cursor-pointer lg:cursor-text focus-visible:outline-(--ui-color-accent-main-primary) focus-visible:outline-2 focus-visible:rounded-[4px] text-legend text-(length:--ui-font-size-lg)/(--ui-font-line-height-3xs) font-(--ui-font-weight-semi-bold) flex-1 flex items-center gap-[6px] lg:shrink-0',
        title: 'line-clamp-1 lg:line-clamp-2',
        trailing: 'ms-auto inline-flex gap-[6px] items-center',
        trailingIcon: 'size-[20px] transform transition-transform duration-200 motion-reduce:transition-none shrink-0 group-data-[state=open]:rotate-180 lg:hidden',
        content: 'relative motion-safe:data-[state=open]:animate-[collapsible-down_200ms_var(--ease-out)] motion-safe:data-[state=closed]:animate-[collapsible-up_200ms_var(--ease-out)] overflow-hidden focus:outline-none lg:min-h-[min(var(--list-height,8rem),16rem)] lg:overflow-y-auto lg:scrollbar-thin lg:scrollbar-transparent',
        list: 'min-w-0',
        listWithChildren: 'ms-[12px]',
        item: 'min-w-0',
        itemWithChildren: '',
        link: 'group relative text-(length:--ui-font-size-lg)/(--ui-font-line-height-3xs) flex items-center focus-visible:outline-(--ui-color-accent-main-primary) focus-visible:outline-1 focus-visible:rounded-[4px] text-description underline-offset-2 hover:text-label hover:underline pb-[12px]',
        linkText: 'line-clamp-2'
      },
      variants: {
        active: {
          false: {
            link: 'text-description hover:text-label transition-colors'
          }
        },
        body: {
          true: {
            bottom: 'mt-6'
          }
        }
      },
      compoundVariants: [
        {
          active: true,
          class: {
            link: 'text-label',
            linkLeadingIcon: 'text-label'
          }
        }
      ],
      defaultVariants: {}
    }
  }
})
```

## Sitemap

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