---
title: "Link"
description: "Обёртка над NuxtLink с дополнительными пропсами."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/link"
---
# Link

> Обёртка над NuxtLink с дополнительными пропсами.

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

Компонент Link — обёртка над [`<NuxtLink>`](https://nuxt.com/docs/api/components/nuxt-link), в которой используется пропс [`custom`](https://router.vuejs.org/api/interfaces/RouterLinkProps.html#Properties-custom). Он добавляет несколько пропсов:

- Пропс `inactive-class` задаёт класс для неактивной ссылки, а `active-class` применяется к активной.
- Пропс `exact` применяет `active-class`, когда ссылка активна и маршрут в точности совпадает с текущим.
- Пропсы `exact-query` и `exact-hash` применяют `active-class`, когда ссылка активна и query или hash в точности совпадают с текущими.

 - `exact-query="partial"` применяет `active-class`, когда ссылка активна и query совпадает с текущим частично.

Цель — предоставить тот же API, что был у NuxtLink в Nuxt 2 / Vue 2. Подробнее об этом — в руководстве Vue Router [по миграции с Vue 2](https://router.vuejs.org/guide/migration/#removal-of-the-exact-prop-in-router-link).

> [!NOTE]
> Его используют компоненты [`Breadcrumb`](https://b24-ui.bx-shef.by/raw/docs/components/breadcrumb.md), [`Button`](https://b24-ui.bx-shef.by/raw/docs/components/button.md), [`ContextMenu`](https://b24-ui.bx-shef.by/raw/docs/components/context-menu.md), [`DropdownMenu`](https://b24-ui.bx-shef.by/raw/docs/components/dropdown-menu.md) и [`NavigationMenu`](https://b24-ui.bx-shef.by/raw/docs/components/navigation-menu.md).

### Тег

Компонент `Link` отрисовывает тег `<a>`, если передан пропс `to`, иначе — тег `<button>`. Пропс `as` меняет запасной тег.

```vue
<template>
  <B24Link as="button">Ссылка</B24Link>
</template>
```

> [!NOTE]
> Изменяя пропс `to`, можно посмотреть на отрисованный HTML.

### Стиль

По умолчанию у ссылки есть стили активного и неактивного состояний, см. раздел [#theme](#theme).

```vue
<template>
  <B24Link to="/docs/components/link/">Ссылка</B24Link>
</template>
```

> [!NOTE]
> Измените пропс `to`, чтобы увидеть активное и неактивное состояния.

Это поведение можно переопределить пропсом `raw` и задать свои стили через `class`, `active-class` и `inactive-class`.

```vue
<template>
  <B24Link raw to="/docs/components/link/" active-class="font-(--ui-font-weight-bold) text-(--ui-color-copilot-accent-primary)" inactive-class="text-(--ui-color-accent-main-alert)">Ссылка</B24Link>
</template>
```

Пропс `is-action` помечает псевдоссылку.

```vue
<template>
  <B24Link is-action to="/docs/components/link/">Ссылка</B24Link>
</template>
```

> [!NOTE]
> Если в VSCode используется расширение [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) и нужно автодополнение для пропсов `active-class` и `inactive-class`, добавьте в `.vscode/settings.json` такие настройки:
> ```json [.vscode/settings.json]
> {
>   "tailwindCSS.classAttributes": [
>     "active-class",
>     "inactive-class"
>   ]
> }
> ```

### Локаль

Компонент Link автоматически интегрируется с [`@nuxtjs/i18n`](https://i18n.nuxtjs.org/), если он установлен. Внутренние ссылки локализуются хелпером `$localePath` без ручной обёртки.

```vue
<template>
  <!-- Автоматически станет /en/about или /fr/about в зависимости от текущей локали -->
  <B24Link to="/about">About</B24Link>
</template>
```

> [!TIP]
> При необходимости `localePath()` или `localeRoute()` можно по-прежнему вызывать вручную.

> [!NOTE]
> See: /docs/getting-started/integrations/i18n/nuxt/#dynamic-locale
> Подробнее об интернационализации в Bitrix24 UI.

## API

### Пропсы

```ts
/**
 * Props for the Link component
 */
interface LinkProps {
  /**
   * The element or component this component should render as when not a link.
   * @default 'button'
   */
  as?: any;
  /**
   * The type of the button when not a link.
   * @default 'button'
   */
  type?: "reset" | "submit" | "button" | undefined;
  disabled?: boolean | undefined;
  /**
   * Force the link to be active independent of the current route.
   * @default undefined
   */
  active?: boolean | undefined;
  /**
   * Will only be active if the current route is an exact match.
   */
  exact?: boolean | undefined;
  /**
   * Allows controlling how the current route query sets the link as active.
   */
  exactQuery?: boolean | "partial" | undefined;
  /**
   * Will only be active if the current route hash is an exact match.
   */
  exactHash?: boolean | undefined;
  /**
   * The class to apply when the link is inactive.
   */
  inactiveClass?: string | undefined;
  /**
   * Whether RouterLink should not wrap its content in an `a` tag. Useful when
   * using `v-slot` to create a custom RouterLink
   */
  custom?: boolean | undefined;
  /**
   * When `true`, uses special underlined styling.
   * @default false
   */
  isAction?: boolean | undefined;
  /**
   * When `true`, only styles from `class`, `activeClass`, and `inactiveClass` will be applied.
   */
  raw?: boolean | undefined;
  /**
   * Control i18n auto-localization when `@nuxtjs/i18n` is installed.
   * - `undefined` / `true` (default): auto-localizes to the current locale using `$localePath`.
   *   Paths already carrying a locale prefix (from e.g. `switchLocalePath()`) are detected
   *   and left untouched to prevent double-prefixing.
   * - `false`: explicitly disables auto-localization.
   * - `string`: localizes to a specific locale (e.g. `'fr'`).
   * @default undefined
   */
  locale?: string | false | true | undefined;
  /**
   * Route Location the link should navigate to when clicked on.
   */
  to?: string | J | W | undefined;
  /**
   * An alias for `to`. If used with `to`, `href` will be ignored
   */
  href?: string | J | W | undefined;
  /**
   * Forces the link to be considered as external (true) or internal (false). This is helpful to handle edge-cases
   */
  external?: boolean | undefined;
  /**
   * Where to display the linked URL, as the name for a browsing context.
   */
  target?: null | string & {} | "_blank" | "_parent" | "_self" | "_top" | undefined;
  /**
   * A rel attribute value to apply on the link. Defaults to "noopener noreferrer" for external links.
   */
  rel?: null | "noopener" | "noreferrer" | "nofollow" | "sponsored" | "ugc" | string & {} | undefined;
  /**
   * If set to true, no rel attribute will be added to the link
   */
  noRel?: boolean | undefined;
  /**
   * A class to apply to links that have been prefetched.
   */
  prefetchedClass?: string | undefined;
  /**
   * When enabled will prefetch middleware, layouts and payloads of links in the viewport.
   */
  prefetch?: boolean | undefined;
  /**
   * Allows controlling when to prefetch links. By default, prefetch is triggered only on visibility.
   */
  prefetchOn?: "visibility" | "interaction" | Partial<{ visibility: boolean; interaction: boolean; }> | undefined;
  /**
   * Escape hatch to disable `prefetch` attribute.
   */
  noPrefetch?: boolean | undefined;
  /**
   * An option to either add or remove trailing slashes in the `href` for this specific link.
   * Overrides the global `trailingSlash` option if provided.
   */
  trailingSlash?: "remove" | "append" | undefined;
  /**
   * Class to apply when the link is active
   */
  activeClass?: string | undefined;
  /**
   * Class to apply when the link is exact active
   */
  exactActiveClass?: string | undefined;
  /**
   * Value passed to the attribute `aria-current` when the link is exact active.
   * @default 'page'
   */
  ariaCurrentValue?: "step" | "page" | "true" | "false" | "location" | "date" | "time" | undefined;
  /**
   * Pass the returned promise of `router.push()` to `document.startViewTransition()` if supported.
   */
  viewTransition?: boolean | undefined;
  /**
   * Calls `router.replace` instead of `router.push`.
   */
  replace?: boolean | undefined;
  name?: string | undefined;
  autofocus?: false | true | "true" | "false" | undefined;
  form?: string | undefined;
  formaction?: string | undefined;
  formenctype?: string | undefined;
  formmethod?: string | undefined;
  formnovalidate?: false | true | "true" | "false" | undefined;
  formtarget?: string | undefined;
  referrerpolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url" | undefined;
  download?: any;
  hreflang?: string | undefined;
  media?: string | undefined;
  ping?: string | undefined;
}
```

> [!NOTE]
> See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attributes
> Компонент поддерживает и все нативные HTML-атрибуты `<a>`.

### Слоты

```ts
/**
 * Slots for the Link component
 */
interface LinkSlots {
  default(): any;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    link: {
      base: 'cursor-pointer focus-visible:outline-(--ui-color-design-outline-focused-stroke) focus-visible:outline-1 focus-visible:rounded-[4px] text-start',
      variants: {
        active: {
          true: 'text-(--ui-color-accent-main-primary) outline-(--ui-color-accent-main-primary) hover:not-disabled:not-aria-disabled:underline underline-offset-2',
          false: 'text-(--ui-color-design-selection-content) underline-offset-2'
        },
        disabled: {
          true: 'cursor-not-allowed opacity-75'
        },
        isAction: {
          true: 'text-nowrap text-(length:--ui-font-size-sm) h-auto py-0 font-(--ui-font-weight-normal) rounded-none border border-x-0 border-t-0 border-dashed text-(--ui-color-design-outline-a1-content) border-b-(--ui-color-design-outline-a1-content) hover:not-disabled:not-aria-disabled:no-underline hover:not-disabled:not-aria-disabled:text-(--ui-color-accent-soft-element-red) hover:border-b-(--ui-color-accent-soft-element-red) focus-visible:outline-(--ui-color-accent-soft-element-red)'
        }
      },
      compoundVariants: [
        {
          active: false,
          disabled: false,
          class: 'hover:text-(--ui-color-accent-main-primary-alt-2) hover:underline'
        }
      ]
    }
  }
})
```

## Sitemap

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