---
title: "<NuxtLink>"
description: "Nuxt 提供 <NuxtLink> 组件来处理应用内的各种链接。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/api/components/nuxt-link"
---
# <NuxtLink>

> Nuxt 提供 <NuxtLink> 组件来处理应用内的各种链接。

<note>

`<NuxtLink>` 是 Vue Router 的 `<RouterLink>` 组件和 HTML 的 `<a>` 标签的直接替代品。它会智能判断链接是 *内部* 还是 *外部*，并根据可用的优化（预取、默认属性等）相应地渲染。

</note>

<read-more title="Nuxt accessibility" to="https://nuxt.zhcndoc.com/docs/4.x/guide/best-practices/accessibility#links">



</read-more>

## 内部路由

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

<code-group>

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

```html [（渲染为）index.html]
<!-- （Vue Router 与智能预取） -->
<a href="/about">关于页面</a>
```

</code-group>

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

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

<code-group>

```vue [app/pages/index.vue]
<template>
  <NuxtLink :to="{ name: 'posts-id', params: { id: 123 } }">
    帖子 123
  </NuxtLink>
</template>
```

```html [（渲染为）index.html]
<a href="/posts/123">帖子 123</a>
```

</code-group>

<tip>

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

</tip>

<tip>

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

</tip>

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

默认情况下，`<NuxtLink>` 对相对路由使用 Vue Router 的客户端导航。当链接到 `/public` 目录下的静态文件或同一域上托管的另一个应用时，可能会导致意外的 404 错误，因为这些不是客户端路由的一部分。在这种情况下，你可以对 `<NuxtLink>` 使用 `external` 属性来绕过 Vue Router 的内部路由机制。

`external` 属性显式表明该链接是外部链接。`<NuxtLink>` 将把链接渲染为标准的 HTML `<a>` 标签。这可以确保链接正常工作，绕过 Vue Router 的逻辑并直接指向资源。

#### 链接到静态文件

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

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

#### 链接到跨应用 URL

当指向同一域上的不同应用时，使用 `external` 属性可确保行为正确。

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

使用 `external` 属性或依赖自动处理可以确保正确导航，避免意外的路由问题，并提高与静态资源或跨应用场景的兼容性。

## 外部路由

在此示例中，我们使用 `<NuxtLink>` 组件链接到一个网站。

```vue [app/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/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/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` 将被忽略。

</note>

## 预取链接

Nuxt 自动包含智能预取。这意味着它会检测链接何时可见（默认情况下），无论是在视口中还是在滚动时，并预取这些页面的 JavaScript，使得在用户点击链接时页面已准备好。Nuxt 仅在浏览器空闲时加载资源，并在连接离线或仅有 2g 网络时跳过预取。

当使用 `custom` 属性时，`<NuxtLink>` 不会自动附加预取处理器。你可以自行从自定义插槽中调用 `prefetch`。

```vue [app/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` 事件。这可能导致不必要的资源使用或重复预取，因为两者触发条件可能会在不同情况下对同一资源进行预取。

当使用 `custom` 时，预取由你的插槽实现来控制 <badge className="align-middle" color="info" size="xs">

v4.5

</badge>

:

```vue
<template>
  <NuxtLink
    v-slot="{ href, navigate, prefetch, shouldPrefetch }"
    to="/about"
    custom
  >
    <a
      :href="href"
      @click="navigate"
      @pointerenter="shouldPrefetch('interaction') && prefetch()"
      @focus="shouldPrefetch('interaction') && prefetch()"
    >
      关于页面
    </a>
  </NuxtLink>
</template>
```

### 启用跨域预取

要启用跨域预取，可以在 `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)

- `to`：任意 URL 或 Vue Router 的[路由位置对象](https://router.vuejs.org/api/type-aliases/routelocation)
- `custom`：是否应该让 `<NuxtLink>` 将其内容包裹在 `<a>` 元素中。它允许完全控制链接的渲染方式以及点击时的导航行为。与 [Vue Router 的 `custom` 属性](https://router.vuejs.org/api/interfaces/routerlinkprops#custom-) 工作方式相同
- `exactActiveClass`：应用于精确激活链接的类。与 [Vue Router 的 `exactActiveClass` 属性](https://router.vuejs.org/api/interfaces/routerlinkprops#exactActiveClass-) 在内部链接上的行为相同。默认为 Vue Router 的默认值（"router-link-exact-active"）
- `activeClass`：应用于激活链接的类。与 [Vue Router 的 `activeClass` 属性](https://router.vuejs.org/api/interfaces/routerlinkprops#activeClass-) 在内部链接上的行为相同。默认为 Vue Router 的默认值（"router-link-active"）
- `replace`：在内部链接上与 [Vue Router 的 `replace` 属性](https://router.vuejs.org/api/interfaces/routelocationoptions#replace-) 行为相同
- `ariaCurrentValue`：在精确激活链接上应用的 `aria-current` 属性值。与 [Vue Router 的 `ariaCurrentValue` 属性](https://router.vuejs.org/api/interfaces/routerlinkprops#ariaCurrentValue-) 在内部链接上的行为相同

### NuxtLink

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

<note>

使用 `custom` 属性时，`prefetch`、`prefetchOn` 和 `prefetchedClass` 不会自动附加处理器或类。请使用自定义插槽的 `prefetch`、`prefetched` 和 `shouldPrefetch` 值来实现此行为。

</note>

### Anchor

- `target`：应用于链接的 `target` 属性值
- `rel`：应用于链接的 `rel` 属性值。外部链接默认值为 `"noopener noreferrer"`

<tip>

默认值可以覆盖；如果你想更改它们，请参阅[覆盖默认值](https://nuxt.zhcndoc.com/docs/4.x/api/components/nuxt-link#overwriting-defaults)。

</tip>

## 覆盖默认值

### 在 Nuxt 配置中

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

<important>

这些选项将来可能会被移到其他位置，例如 `app.config` 或 `app/` 目录中。

</important>

```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 [app/components/MyNuxtLink.ts]
export default defineNuxtLink({
  componentName: 'MyNuxtLink',
  /* 更多信息请参见下面的签名 */
})
```

该组件会根据其文件名自动导入，因此你可以像往常一样使用 `<MyNuxtLink />`，同时应用你新的默认值。`componentName` 只会设置组件的内部名称（如 Vue DevTools 中所示）；它不会改变组件在模板中的使用方式。

### `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`：组件的内部名称，如 Vue DevTools 中所示。它不会改变模板中使用的名称（该名称来自组件的文件名）。默认为 `NuxtLink`。
- `externalRelAttribute`：应用于外部链接的默认 `rel` 属性值。默认为 `"noopener noreferrer"`。将其设为 `""` 可禁用
- `activeClass`：应用于激活链接的默认类。其工作方式与 [Vue Router 的 `linkActiveClass` 选项](https://router.vuejs.org/api/interfaces/routeroptions#linkActiveClass-) 相同。默认为 Vue Router 的默认值（`"router-link-active"`）
- `exactActiveClass`：应用于精确激活链接的默认类。其工作方式与 [Vue Router 的 `linkExactActiveClass` 选项](https://router.vuejs.org/api/interfaces/routeroptions#linkExactActiveClass-) 相同。默认为 Vue Router 的默认值（`"router-link-exact-active"`）
- `trailingSlash`：用于在 `href` 中添加或移除尾部斜杠的选项。如果未设置，或不匹配有效值 `append` 或 `remove`，则会被忽略。
- `prefetch`：是否默认预取链接。
- `prefetchOn`：对默认应用哪些预取策略进行细粒度控制。
- `prefetchedClass`：应用于已被预取链接的默认类。

<link-example to="https://nuxt.zhcndoc.com/docs/4.x/examples/routing/pages">



</link-example>

---

- [源码](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.
