Link

GitLab
Um wrapper em torno de com props extras.

Uso

O componente Link é um wrapper em torno do <NuxtLink> usando a prop custom. Ele fornece algumas props extras:

  • inactive-class prop to set a class when the link is inactive, active-class is used when active.
  • exact prop to style with active-class when the link is active and the route is exactly the same as the current route.
  • exact-query and exact-hash props to style with active-class when the link is active and the query or hash is exactly the same as the current query or hash.
    • use exact-query="partial" to style with active-class when the link is active and the query partially match the current query.

A motivação por trás disso é oferecer a mesma API do NuxtLink dos tempos do Nuxt 2 / Vue 2. Você pode ler mais sobre isso no guia de migração do Vue 2 do Vue Router.

Ele é usado pelos componentes Breadcrumb, Button, ContextMenu, DropdownMenu e NavigationMenu.

Tag

O componente Link renderiza uma tag <a> quando uma prop to é fornecida; caso contrário, renderiza uma tag <button>. Você pode usar a prop as para alterar a tag de fallback.

<template>
  <NLink as="button">Link</NLink>
</template>
Você pode inspecionar o HTML renderizado alterando a prop to.

Estilo

Por padrão, o link tem estilos de ativo e inativo padrão; confira a seção #theme.

<template>
  <NLink to="/docs/components/link">Link</NLink>
</template>
Tente alterar a prop to para ver os estados ativo e inativo.

Você pode sobrescrever esse comportamento usando a prop raw e fornecer seus próprios estilos usando class, active-class e inactive-class.

<template>
  <NLink raw to="/docs/components/link" active-class="font-bold" inactive-class="text-muted">Link</NLink>
</template>
Se você está usando a extensão Tailwind CSS IntelliSense para o VSCode e quer ter autocompletar para as props active-class e inactive-class, você pode adicionar as seguintes configurações ao seu .vscode/settings.json:
.vscode/settings.json
{
  "tailwindCSS.classAttributes": [
    "active-class",
    "inactive-class"
  ]
}

Locale 4.7+

O componente Link se integra automaticamente ao @nuxtjs/i18n quando instalado. Os links internos são localizados automaticamente usando o helper $localePath, sem exigir envolvimento manual.

<template>
  <!-- Automatically becomes /en/about or /fr/about based on current locale -->
  <NLink to="/about">About</NLink>
</template>
Você ainda pode usar localePath() ou localeRoute() manualmente se necessário.
Learn more about Internationalization in Nitro UI.

API

Props

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.

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 | it | et

Route Location the link should navigate to when clicked on.

href string | it | et

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
Este componente também suporta todos os atributos HTML nativos de <a>.

Slots

Slot Type
default{ active: boolean; }

Tema

app.config.ts
export default defineAppConfig({
  ui: {
    link: {
      base: 'focus-visible:outline-accent underline underline-offset-2',
      variants: {
        active: {
          true: 'text-accent',
          false: ''
        },
        disabled: {
          true: 'cursor-not-allowed opacity-75'
        }
      },
      compoundVariants: [
        {
          active: false,
          disabled: false,
          class: 'hover:text-accent transition-colors'
        }
      ]
    }
  }
})
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ui from '@nitro/ui/vite'

export default defineConfig({
  plugins: [
    vue(),
    ui({
      ui: {
        link: {
          base: 'focus-visible:outline-accent underline underline-offset-2',
          variants: {
            active: {
              true: 'text-accent',
              false: ''
            },
            disabled: {
              true: 'cursor-not-allowed opacity-75'
            }
          },
          compoundVariants: [
            {
              active: false,
              disabled: false,
              class: 'hover:text-accent transition-colors'
            }
          ]
        }
      }
    })
  ]
})

Changelog

No recent changes