<NuxtLink>

Исходники
Nuxt предоставляет компонент <NuxtLink> для обработки любых видов ссылок в вашем приложении.
<NuxtLink> - это встроенная замена как компонента Vue Router <RouterLink>, так и HTML-тега <a>. Он умно определяет, является ли ссылка внутренней или внешней, и рендерит ее соответствующим образом с помощью доступных оптимизаций (предварительная загрузка, атрибуты по умолчанию и т.д.)

Внутренний роутинг

В этом примере мы используем компонент <NuxtLink> для перехода на другую страницу приложения.

<template>
  <NuxtLink to="/about">About page</NuxtLink>
</template>

Передача параметров динамическим маршрутам

В этом примере мы передаем параметр id для ссылки на маршрут ~/pages/posts/[id].vue.

<template>
  <NuxtLink :to="{ name: 'posts-id', params: { id: 123 } }">
    Post 123
  </NuxtLink>
</template>
Проверьте панель Pages в Nuxt DevTools, чтобы увидеть название маршрута и параметры, которые он может принять.
When you pass an object into the to prop, <NuxtLink> will inherit Vue Router’s handling of query parameters. Keys and values will be automatically encoded, so you don’t need to call encodeURI or encodeURIComponent manually.

By default, <NuxtLink> uses Vue Router's client side navigation for relative route. When linking to static files in the /public directory or to another application hosted on the same domain, it might result in unexpected 404 errors because they are not part of the client routes. In such cases, you can use the external prop with <NuxtLink> to bypass Vue Router's internal routing mechanism.

The external prop explicitly indicates that the link is external. <NuxtLink> will render the link as a standard HTML <a> tag. This ensures the link behaves correctly, bypassing Vue Router’s logic and directly pointing to the resource.

Linking to Static Files

For static files in the /public directory, such as PDFs or images, use the external prop to ensure the link resolves correctly.

pages/index.vue
<template>
  <NuxtLink to="/example-report.pdf" external>
    Download Report
  </NuxtLink>
</template>

Linking to a Cross-App URL

When pointing to a different application on the same domain, using the external prop ensures the correct behavior.

pages/index.vue
<template>
  <NuxtLink to="/another-app" external>
    Go to Another App
  </NuxtLink>
</template>

Using the external prop or relying on automatic handling ensures proper navigation, avoids unexpected routing issues, and improves compatibility with static resources or cross-application scenarios.

Внешний роутинг

В этом примере мы используем компонент <NuxtLink> для перехода по ссылке на веб-сайт.

app.vue
<template>
  <NuxtLink to="https://nuxtjs.org">
    Nuxt website
  </NuxtLink>
  <!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>

Атрибуты rel и noRel

A rel attribute of noopener noreferrer is applied by default to links with a target attribute or to absolute links (e.g., links starting with http://, https://, or //).

  • noopener устраняет ошибку безопасности в старых браузерах.
  • noreferrer улучшает конфиденциальность для ваших пользователей, не отправляя заголовок Referer на сайт, на который дана ссылка.

Эти значения по умолчанию не оказывают негативного влияния на SEO и считаются лучшей практикой.

Когда вам нужно перезаписать это поведение, вы можете использовать входные параметры rel или noRel.

app.vue
<template>
  <NuxtLink to="https://twitter.com/nuxt_js">
    Nuxt Twitter
  </NuxtLink>
  <!-- <a href="https://twitter.com/nuxt_js" rel="noopener noreferrer">...</a> -->

  <NuxtLink to="https://discord.nuxtjs.org" rel="noopener">
    Nuxt Discord
  </NuxtLink>
  <!-- <a href="https://discord.nuxtjs.org" rel="noopener">...</a> -->

  <NuxtLink to="/about" target="_blank">About page</NuxtLink>
  <!-- <a href="/about" target="_blank" rel="noopener noreferrer">...</a> -->
</template>

A noRel prop can be used to prevent the default rel attribute from being added to the absolute links.

app.vue
<template>
  <NuxtLink to="https://github.com/nuxt" no-rel>
    Nuxt GitHub
  </NuxtLink>
  <!-- <a href="https://github.com/nuxt">...</a> -->
</template>
noRel and rel cannot be used together. rel will be ignored.

Nuxt automatically includes smart prefetching. That means it detects when a link is visible (by default), either in the viewport or when scrolling and prefetches the JavaScript for those pages so that they are ready when the user clicks the link. Nuxt only loads the resources when the browser isn't busy and skips prefetching if your connection is offline or if you only have 2g connection.

pages/index.vue
<NuxtLink to="/about" no-prefetch>About page not pre-fetched</NuxtLink>
<NuxtLink to="/about" :prefetch="false">About page not pre-fetched</NuxtLink>

Custom Prefetch Triggers

We now support custom prefetch triggers for <NuxtLink> after v3.13.0. You can use the prefetchOn prop to control when to prefetch links.

<template>
  <NuxtLink prefetch-on="visibility">
    This will prefetch when it becomes visible (default)
  </NuxtLink>

  <NuxtLink prefetch-on="interaction">
    This will prefetch when hovered or when it gains focus
  </NuxtLink>
</template>
  • visibility: Prefetches when the link becomes visible in the viewport. Monitors the element's intersection with the viewport using the Intersection Observer API. Prefetching is triggered when the element is scrolled into view.
  • interaction: Prefetches when the link is hovered or focused. This approach listens for pointerenter and focus events, proactively prefetching resources when the user indicates intent to interact.

You can also use an object to configure prefetchOn:

<template>
  <NuxtLink :prefetch-on="{ interaction: true }">
    This will prefetch when hovered or when it gains focus
  </NuxtLink>
</template>

That you probably don't want both enabled!

<template>
  <NuxtLink :prefetch-on="{ visibility: true, interaction: true }">
    This will prefetch when hovered/focus - or when it becomes visible
  </NuxtLink>
</template>

This configuration will observe when the element enters the viewport and also listen for pointerenter and focus events. This may result in unnecessary resource usage or redundant prefetching, as both triggers can prefetch the same resource under different conditions.

Enable Cross-origin Prefetch

To enable cross-origin prefetching, you can set the crossOriginPrefetch option in your nuxt.config. This will enable cross-origin prefetching using the Speculation Rules API.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    crossOriginPrefetch: true,
  },
})

Disable prefetch globally

It's also possible to enable/disable prefetching all links globally for your app.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    defaults: {
      nuxtLink: {
        prefetch: false,
      },
    },
  },
})

Входные параметры

Если не используется external, <NuxtLink> поддерживает все входные параметры RouterLink от Vue Router

  • to: Any URL or a route location object from Vue Router
  • custom: Whether <NuxtLink> should wrap its content in an <a> element. It allows taking full control of how a link is rendered and how navigation works when it is clicked. Works the same as Vue Router's custom prop
  • exactActiveClass: A class to apply on exact active links. Works the same as Vue Router's exactActiveClass prop on internal links. Defaults to Vue Router's default ("router-link-exact-active")
  • activeClass: A class to apply on active links. Works the same as Vue Router's activeClass prop on internal links. Defaults to Vue Router's default ("router-link-active")
  • replace: Works the same as Vue Router's replace prop on internal links
  • ariaCurrentValue: An aria-current attribute value to apply on exact active links. Works the same as Vue Router's ariaCurrentValue prop on internal links
  • href: Алиас для to. При использовании to, href будет проигнорирован
  • noRel: Если установлено в true, атрибут rel не будет добавлен к внешней ссылке
  • external: Заставляет ссылку рендериться как тег a вместо RouterLink у Vue Router.
  • prefetch: Когда включено, будет выполняться предварительная загрузка middleware, layouts и payloads (при использовании payloadExtraction) ссылок в области просмотра. Используется в экспериментальной конфигурации crossOriginPrefetch.
  • prefetchOn: Allows custom control of when to prefetch links. Possible options are interaction and visibility (default). You can also pass an object for full control, for example: { interaction: true, visibility: true }. This prop is only used when prefetch is enabled (default) and noPrefetch is not set.
  • noPrefetch: Отключает предварительную загрузку.
  • prefetchedClass: Класс, применяемый к ссылкам, которые были предварительно загружены.

Якорь

  • target: Значение атрибута target, применяемое к ссылке.
  • rel: Значение атрибута rel, применяемое к ссылке. По умолчанию для внешних ссылок используется "noopener noreferrer".
Значения по умолчанию могут быть перезаписаны, см. раздел перезапись значений по умолчанию, если вы хотите их изменить.

Перезапись значений по умолчанию

В Nuxt Config

Вы можете перезаписать некоторые значения по умолчанию для <NuxtLink> в вашем nuxt.config

Скорее всего, в будущем эти параметры будут перенесены в другое место, например, в app.config или в директорию app/.
nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    defaults: {
      nuxtLink: {
        // значения по умолчанию
        componentName: 'NuxtLink',
        externalRelAttribute: 'noopener noreferrer',
        activeClass: 'router-link-active',
        exactActiveClass: 'router-link-exact-active',
        prefetchedClass: undefined, // может быть любым допустимым строковым именем класса
        trailingSlash: undefined, // может быть 'append' или 'remove'
        prefetch: true,
        prefetchOn: { visibility: true } 
      }
    }
  }
})

Пользовательский компонент ссылки

Вы можете перезаписать значения по умолчанию <NuxtLink>, создав свой собственный компонент ссылок с помощью defineNuxtLink.

components/MyNuxtLink.ts
export default defineNuxtLink({
  componentName: 'MyNuxtLink',
  /* подробнее смотрите в сигнатуре ниже */
})

Затем вы можете использовать компонент <MyNuxtLink /> как обычно с вашими новыми настройками по умолчанию.

interface NuxtLinkOptions {
  componentName?: string;
  externalRelAttribute?: string;
  activeClass?: string;
  exactActiveClass?: string;
  trailingSlash?: 'append' | 'remove'
  prefetch?: boolean
  prefetchedClass?: string
  prefetchOn?: Partial<{
    visibility: boolean
    interaction: boolean
  }>
}
function defineNuxtLink(options: NuxtLinkOptions): Component {}
  • componentName: Имя компонента. По умолчанию используется NuxtLink.
  • externalRelAttribute: Значение атрибута rel по умолчанию, применяемое к внешним ссылкам. По умолчанию используется "noopener noreferrer". Установите значение "", чтобы отключить
  • activeClass: Класс по умолчанию, применяемый к активным ссылкам. Работает так же, как и параметр linkActiveClass у Vue Router. По умолчанию используется значение по умолчанию от Vue Router ("router-link-active")
  • exactActiveClass: Класс по умолчанию, применяемый к точным активным ссылкам. Работает так же, как и параметр linkExactActiveClass у Vue Router. По умолчанию используется значение по умолчанию от Vue Router ("router-link-exact-active")
  • trailingSlash: Возможность добавлять или удалять слэши в конце в href. Если значение не задано или не соответствует допустимым значениям append или remove, оно будет проигнорировано.
  • prefetch: Whether or not to prefetch links by default.
  • prefetchOn: Granular control of which prefetch strategies to apply by default.
  • prefetchedClass: A default class to apply to links that have been prefetched.
Прочитайте и отредактируйте живой пример в Docs > Examples > Routing > Pages.