---
title: "<NuxtLink>"
description: "Nuxt 提供了 <NuxtLink> 组件，用于处理应用程序中的各种链接。"
canonical_url: "https://nuxt.zhcndoc.com/docs/3.x/api/components/nuxt-link"
---
# \<NuxtLink>

> Nuxt 提供了 \<NuxtLink> 组件，用于处理应用程序中的各种链接。

::note
`<NuxtLink>` 是 Vue Router 的 `<RouterLink>` 组件和 HTML 的 `<a>` 标签的替代方案。它能智能判断链接是内部链接还是外部链接，并依据情况优化渲染（预取、默认属性等）。
::

## 内部路由

在此示例中，我们使用 `<NuxtLink>` 组件链接到应用的另一页面。

::code-group
```vue [pages/index.vue]
<template>
  <NuxtLink to="/about">关于页面</NuxtLink>
</template>
```

```html [(Renders as) index.html]
<!-- (Vue Router & 智能预取) -->
<a href="/about">关于页面</a>
```
::

### 向动态路由传递参数

这个示例中，我们传递 `id` 参数链接到路由 `~/pages/posts/[id].vue`。

::code-group
```vue [pages/index.vue]
<template>
  <NuxtLink :to="{ name: 'posts-id', params: { id: 123 } }">
    文章 123
  </NuxtLink>
</template>
```

```html [(Renders as) index.html]
<a href="/posts/123">文章 123</a>
```
::

::tip
查看 Nuxt DevTools 中的 Pages 面板，可以看到路由名称及其可能接受的参数。
::

::tip
当你将一个对象传递给 `to` 属性时，`<NuxtLink>` 将继承 Vue Router 对查询参数的处理。键和值将自动编码，因此你不需要手动调用 `encodeURI` 或 `encodeURIComponent`。
::

### 静态文件及跨应用链接处理

默认情况下，`<NuxtLink>` 使用 Vue Router 的客户端路由导航处理相对路由。链接到 `/public` 目录中的静态文件或同域的其他应用时，可能会出现意外的 404 错误，因为这些文件不属于客户端路由。在这种情况下，可以给 `<NuxtLink>` 添加 `external` 属性，以跳过 Vue Router 的内部路由机制。

`external` 属性显式表示该链接为外部链接，`<NuxtLink>` 会渲染为标准 HTML `<a>` 标签。这样即可确保链接正确跳转，绕过 Vue Router 的路由逻辑，直接指向目标资源。

#### 链接静态文件

对于 `/public` 目录下的静态文件（如 PDF 或图片），可使用 `external` 属性确保链接正确解析。

```vue [pages/index.vue]
<template>
  <NuxtLink to="/example-report.pdf" external>
    下载报告
  </NuxtLink>
</template>
```

#### 链接跨应用 URL

链接同域的不同应用时，使用 `external` 属性确保正确跳转。

```vue [pages/index.vue]
<template>
  <NuxtLink to="/another-app" external>
    前往另一个应用
  </NuxtLink>
</template>
```

使用 `external` 属性或依赖自动检测，能保证导航正常，避免意外的路由问题，并提升与静态资源或跨应用场景的兼容性。

## 外部路由

此示例中，使用 `<NuxtLink>` 组件链接至网站。

```vue [app.vue]
<template>
  <NuxtLink to="https://nuxtjs.org">
    Nuxt 网站
  </NuxtLink>
  <!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>
```

## `rel` 和 `noRel` 属性

带有 `target` 属性或绝对链接（例如以 `http://`、`https://` 或 `//` 开头的链接）默认会添加 `rel="noopener noreferrer"` 属性。

- `noopener` 解决了旧浏览器中的[安全漏洞](https://mathiasbynens.github.io/rel-noopener/)。
- `noreferrer` 保护用户隐私，不向链接站点发送 `Referer` 请求头。

这些默认设置不会对 SEO 产生负面影响，且被认为是[最佳实践](https://developer.chrome.com/docs/lighthouse/best-practices/external-anchors-use-rel-noopener)。

若需覆盖此行为，可使用 `rel` 或 `noRel` 属性。

```vue [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"
  >关于页面</NuxtLink>
  <!-- <a href="/about" target="_blank" rel="noopener noreferrer">...</a> -->
</template>
```

可通过 `noRel` 属性防止默认的 `rel` 属性被加在外链上。

```vue [app.vue]
<template>
  <NuxtLink
    to="https://github.com/nuxt"
    no-rel
  >
    Nuxt GitHub
  </NuxtLink>
  <!-- <a href="https://github.com/nuxt">...</a> -->
</template>
```

::note
`noRel` 和 `rel` 不能同时使用。`rel` 将被忽略。
::

## 预取链接

Nuxt 自动包含智能预取功能，默认检测链接的可视状态（出现在视口内或滚动时），预加载对应页面的 JavaScript，使页面在点击时立即可用。Nuxt 仅在浏览器空闲时加载资源，且在离线或网络仅为 2G 时跳过预取。

```vue [pages/index.vue]
<NuxtLink to="/about" no-prefetch>
关于页面不预取
</NuxtLink>

<NuxtLink to="/about" :prefetch="false">
关于页面不预取
</NuxtLink>
```

### 自定义预取触发条件

从 `v3.13.0` 起，支持对应 `<NuxtLink>` 的自定义预取触发。使用 `prefetchOn` 属性控制预取时机。

```vue
<template>
  <NuxtLink prefetch-on="visibility">
    当链接变为可视时预取（默认）
  </NuxtLink>

  <NuxtLink prefetch-on="interaction">
    当链接被悬停或获得焦点时预取
  </NuxtLink>
</template>
```

- `visibility`：当链接进入视口时预取。通过 [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) 检测元素与视口的交叉情况，滚动到视口时触发预取。
- `interaction`：当链接被鼠标悬停或聚焦时预取。监听 `pointerenter` 和 `focus` 事件，主动在用户有交互意图时提前加载资源。

你也可以使用对象形式来配置 `prefetchOn`：

```vue
<template>
  <NuxtLink :prefetch-on="{ interaction: true }">
    当悬停或聚焦时预取
  </NuxtLink>
</template>
```

通常你不想两者都启用！

```vue
<template>
  <NuxtLink :prefetch-on="{ visibility: true, interaction: true }">
    悬停/聚焦或变为可视时都会预取
  </NuxtLink>
</template>
```

该配置既监听元素进入视口，也监听 `pointerenter` 和 `focus` 事件，可能导致多余资源加载或重复预取，因为两个触发条件在不同场景下均会预取相同资源。

### 启用跨源预取

通过在 `nuxt.config` 中设置 `crossOriginPrefetch` 选项启用跨源预取，借助[Speculation Rules API](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API)实现。

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

### 全局禁用预取

你也可以全局开启/关闭针对所有链接的预取功能。

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

## 属性

### RouterLink

当未使用 `external` 时，`<NuxtLink>` 支持所有 Vue Router 的 [`RouterLink` 属性](https://router.vuejs.org/api/interfaces/RouterLinkProps.html)

- `to`：任何 URL 或 Vue Router 的[路由位置对象](https://router.vuejs.org/api/#RouteLocation)
- `custom`：是否由 `<NuxtLink>` 使用 `<a>` 标签包裹内容。允许完全控制链接渲染及点击导航行为。行为与 Vue Router 的 `custom` 属性一致。
- `exactActiveClass`：精确激活链接时应用的 class。行为同 Vue Router `exactActiveClass` 属性，默认 `"router-link-exact-active"`
- `activeClass`：激活链接时应用的 class。行为同 Vue Router `activeClass` 属性，默认 `"router-link-active"`
- `replace`：与 Vue Router 的 `replace` 属性相同，控制导航是否替换历史记录。
- `ariaCurrentValue`：精确激活链接时应用的 `aria-current` 属性值。行为同 Vue Router 的对应属性。

### NuxtLink {#nuxtlink}

- `href`：`to` 的别名。如果与 `to` 一起使用，将忽略 `href`
- `noRel`：如果设为 `true`，则不会向外部链接添加 `rel` 属性
- `external`：强制将链接渲染为 `<a>` 标签，而不是 Vue Router 的 `RouterLink`。
- `prefetch`：启用后，将预取视口中链接的中间件、布局和负载（使用 [payloadExtraction](https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/experimental-features#payloadextraction) 时）。供实验性的 [crossOriginPrefetch](https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/experimental-features#crossoriginprefetch) 配置使用。
- `prefetchOn`：允许自定义控制链接的预取时机。可选项为 `interaction` 和 `visibility`（默认值）。你也可以传入对象来进行完全控制，例如：`{ interaction: true, visibility: true }`。仅当 `prefetch` 已启用（默认值）且未设置 `noPrefetch` 时，才会使用此属性。
- `noPrefetch`：禁用预取。
- `prefetchedClass`：应用于已预取链接的 class。

### 锚点

- `target`：链接的 `target` 属性值。
- `rel`：链接的 `rel` 属性值。默认对外链添加 `"noopener noreferrer"`。

::tip
如果想修改这些默认值，可以覆盖默认值，参见[覆盖默认值](https://nuxt.zhcndoc.com/docs/3.x/api/components/nuxt-link#overwriting-defaults)。
::

## 覆盖默认值

### 在 Nuxt 配置中

你可以在 [`nuxt.config`](https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/experimental-features#defaults) 中覆盖某些 `<NuxtLink>` 默认值

::important
这些选项未来可能移动到其他位置，如 `app.config` 或 `app/` 目录下。
::

```ts [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 },
      },
    },
  },
})
```

### 自定义链接组件

也可以通过 `defineNuxtLink` 自定义链接组件并覆盖 `<NuxtLink>` 的默认行为。

```ts [components/MyNuxtLink.ts]
export default defineNuxtLink({
  componentName: 'MyNuxtLink',
  /* 更多配置见下方签名 */
})
```

然后即可像平常一样使用 `<MyNuxtLink />` 组件，拥有你新的默认配置。

### `defineNuxtLink` 签名

```ts
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`：激活链接默认应用的 class，行为同 Vue Router 的 `linkActiveClass`。默认 `"router-link-active"`。
- `exactActiveClass`：精确激活链接默认应用的 class，行为同 Vue Router 的 `linkExactActiveClass`。默认 `"router-link-exact-active"`。
- `trailingSlash`：控制 `href` 是否添加（或移除）结尾斜杠。无效设置将被忽略。
- `prefetch`：是否默认启用预取。
- `prefetchOn`：默认预取触发策略的详细控制。
- `prefetchedClass`：预取完成后应用的默认 class。

::link-example{to="https://nuxt.zhcndoc.com/docs/examples/routing/pages"}
::

---

- [源码](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-link.ts)


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
