v2.15.0

Link

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

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

Компонент Link — обёртка над <NuxtLink>, в которой используется пропс 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.

Его используют компоненты Breadcrumb, Button, ContextMenu, DropdownMenu и NavigationMenu.

Тег

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

<template>
  <B24Link as="button">Ссылка</B24Link>
</template>
Изменяя пропс to, можно посмотреть на отрисованный HTML.

Стиль

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

<template>
  <B24Link to="/docs/components/link/">Ссылка</B24Link>
</template>
Измените пропс to, чтобы увидеть активное и неактивное состояния.

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

<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 помечает псевдоссылку.

<template>
  <B24Link is-action to="/docs/components/link/">Ссылка</B24Link>
</template>
Если в VSCode используется расширение Tailwind CSS IntelliSense и нужно автодополнение для пропсов active-class и inactive-class, добавьте в .vscode/settings.json такие настройки:
.vscode/settings.json
{
  "tailwindCSS.classAttributes": [
    "active-class",
    "inactive-class"
  ]
}

Локаль

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

<template>
  <!-- Автоматически станет /en/about или /fr/about в зависимости от текущей локали -->
  <B24Link to="/about">About</B24Link>
</template>
При необходимости localePath() или localeRoute() можно по-прежнему вызывать вручную.
Подробнее об интернационализации в Bitrix24 UI.

API

Пропсы

Prop Default Type
as'button'any

The element or component this component should render as when not a link.

type'button' "reset" | "submit" | "button"

The type of the button when not a link.

disabledboolean
activeundefinedboolean

Force the link to be active independent of the current route.

exactboolean

Will only be active if the current route is an exact match.

exactQueryboolean | "partial"

Allows controlling how the current route query sets the link as active.

exactHashboolean

Will only be active if the current route hash is an exact match.

inactiveClass string

The class to apply when the link is inactive.

isActionfalseboolean

When true, uses special underlined styling.

rawboolean

When true, only styles from class, activeClass, and inactiveClass will be applied.

localeundefined string | false | true

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').
to string | J | W

Route Location the link should navigate to when clicked on.

href string | J | W

An alias for to. If used with to, href will be ignored

externalboolean

Forces the link to be considered as external (true) or internal (false). This is helpful to handle edge-cases

target null | string & {} | "_blank" | "_parent" | "_self" | "_top"

Where to display the linked URL, as the name for a browsing context.

rel null | "noopener" | "noreferrer" | "nofollow" | "sponsored" | "ugc" | string & {}

A rel attribute value to apply on the link. Defaults to "noopener noreferrer" for external links.

noRelboolean

If set to true, no rel attribute will be added to the link

prefetchedClass string

A class to apply to links that have been prefetched.

prefetchboolean

When enabled will prefetch middleware, layouts and payloads of links in the viewport.

prefetchOn "visibility" | "interaction" | Partial<{ visibility: boolean; interaction: boolean; }>

Allows controlling when to prefetch links. By default, prefetch is triggered only on visibility.

noPrefetchboolean

Escape hatch to disable prefetch attribute.

trailingSlash "remove" | "append"

An option to either add or remove trailing slashes in the href for this specific link. Overrides the global trailingSlash option if provided.

activeClass string

Class to apply when the link is active

exactActiveClass string

Class to apply when the link is exact active

ariaCurrentValue'page' "step" | "page" | "true" | "false" | "location" | "date" | "time"

Value passed to the attribute aria-current when the link is exact active.

viewTransitionboolean

Pass the returned promise of router.push() to document.startViewTransition() if supported.

replaceboolean

Calls router.replace instead of router.push.

name string
autofocus false | true | "true" | "false"
form string
formaction string
formenctype string
formmethod string
formnovalidate false | true | "true" | "false"
formtarget string
referrerpolicy "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"
downloadany
hreflang string
media string
ping string
Компонент поддерживает и все нативные HTML-атрибуты <a>.

Слоты

Slot Type
default{ active: boolean; }

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/link.ts
export default {
  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'
    }
  ]
}