---
title: "SEO 和元数据"
description: "通过强大的 head 配置、组合函数和组件提升您的 Nuxt 应用的 SEO。"
canonical_url: "https://nuxt.zhcndoc.com/docs/3.x/getting-started/seo-meta"
---
# SEO 和元数据

> 通过强大的 head 配置、组合函数和组件提升您的 Nuxt 应用的 SEO。

Nuxt 的 head 标签管理由 [Unhead](https://unhead.unjs.io) 提供支持。它提供了合理的默认值、多个强大的组合函数以及丰富的配置选项，用于管理您的应用的 head 和 SEO 元标签。

## Nuxt 配置

在 [`nuxt.config.ts`](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/nuxt-config) 中提供 [`app.head`](https://nuxt.zhcndoc.com/docs/3.x/api/nuxt-config#head) 属性，即可静态自定义整个应用的 head。

::important
此方法不支持提供响应式数据。我们推荐在 `app.vue` 中使用 `useHead()`。
::

通常建议在这里设置不会改变的标签，例如您的网站默认标题、语言和 favicon。

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  app: {
    head: {
      title: 'Nuxt', // 默认回退标题
      htmlAttrs: {
        lang: 'en',
      },
      link: [
        { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      ],
    },
  },
})
```

您也可以提供 [类型](https://nuxt.zhcndoc.com/docs/3.x/getting-started/seo-meta#types) 中列出的任意键。

### 默认标签

Nuxt 默认会提供一些标签，以确保您的网站开箱即用地正常工作。

- `viewport`：`width=device-width, initial-scale=1`
- `charset`：`utf-8`

虽然大多数站点不需要重写这些默认值，但您可以使用键控的快捷方式来更新它们。

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  app: {
    head: {
      // 更新 Nuxt 默认值
      charset: 'utf-16',
      viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
    },
  },
})
```

## `useHead`

[`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head) 组合函数支持响应式输入，让您可以通过编程方式管理 head 标签。

```vue twoslash [app.vue]
<script setup lang="ts">
useHead({
  title: 'My App',
  meta: [
    { name: 'description', content: 'My amazing site.' },
  ],
  bodyAttrs: {
    class: 'test',
  },
  script: [{ innerHTML: 'console.log(\'Hello world\')' }],
})
</script>
```

我们建议您了解 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head) 和 [`useHeadSafe`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head-safe) 组合函数。

## `useSeoMeta`

[`useSeoMeta`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-seo-meta) 组合函数可让您以具有完整类型安全性的对象形式定义网站的 SEO 元标签。

这可以帮助您避免拼写错误和常见错误，例如使用 `name` 而非 `property`。

```vue twoslash [app.vue]
<script setup lang="ts">
useSeoMeta({
  title: 'My Amazing Site',
  ogTitle: 'My Amazing Site',
  description: 'This is my amazing site, let me tell you all about it.',
  ogDescription: 'This is my amazing site, let me tell you all about it.',
  ogImage: 'https://example.com/image.png',
  twitterCard: 'summary_large_image',
})
</script>
```

::read-more{to="https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-seo-meta"}
::

## 组件

虽然在所有情况下都推荐使用 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head)，但您也可能更喜欢在模板中使用组件定义 head 标签。

Nuxt 提供以下组件供此用途：`<Title>`、`<Base>`、`<NoScript>`、`<Style>`、`<Meta>`、`<Link>`、`<Body>`、`<Html>` 以及 `<Head>`。请注意这些组件均首字母大写，以避免使用无效的原生 HTML 标签。

`<Head>` 和 `<Body>` 可以接受嵌套的元标签（出于美观考虑），但这不会影响嵌套标签在最终 HTML 中的渲染位置。

<!-- @case-police-ignore html -->

```vue [app.vue]
<script setup lang="ts">
const title = ref('Hello World')
</script>

<template>
  <div>
    <Head>
      <Title>{{ title }}</Title>
      <Meta
        name="description"
        :content="title"
      />
      <Style>
        body { background-color: green; }
      </Style>
    </Head>

    <h1>{{ title }}</h1>
  </div>
</template>
```

建议将组件包裹于 `<Head>` 或 `<Html>` 组件中，这样标签会更直观地去重。

::warning
如果需要在客户端和服务器端之间重复标签，请在 `<Head>` 组件上应用 `key` 属性。
::

## 类型

以下是 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head)、[`app.head`](https://nuxt.zhcndoc.com/docs/3.x/api/nuxt-config#head) 和组件使用的非响应式类型。

```ts
interface MetaObject {
  title?: string
  titleTemplate?: string | ((title?: string) => string)
  templateParams?: Record<string, string | Record<string, string>>
  base?: Base
  link?: Link[]
  meta?: Meta[]
  style?: Style[]
  script?: Script[]
  noscript?: Noscript[]
  htmlAttrs?: HtmlAttributes
  bodyAttrs?: BodyAttributes
}
```

更多详细类型请参见 [@unhead/vue](https://github.com/unjs/unhead/blob/main/packages/vue/src/types/schema.ts)。

## 特性

### 响应性

通过提供计算值、getter 或响应式对象，所有属性均支持响应性。

::code-group
```vue twoslash [useHead]
<script setup lang="ts">
const description = ref('My amazing site.')

useHead({
  meta: [
    { name: 'description', content: description },
  ],
})
</script>
```

```vue twoslash [useSeoMeta]
<script setup lang="ts">
const description = ref('My amazing site.')

useSeoMeta({
  description,
})
</script>
```

```vue [Components]
<script setup lang="ts">
const description = ref('My amazing site.')
</script>

<template>
  <div>
    <Meta
      name="description"
      :content="description"
    />
  </div>
</template>
```
::

### 标题模板

您可以使用 `titleTemplate` 选项为站点标题提供动态模板。例如，您可以将站点名称添加到每个页面的标题中。

`titleTemplate` 可以是字符串，其中 `%s` 会被标题替代，也可以是函数。

如果要使用函数（以获得完全控制），则不能在 `nuxt.config` 中设置。建议在 `app.vue` 文件中设置，这样它会应用于站点上的所有页面：

::code-group
```vue twoslash [useHead]
<script setup lang="ts">
useHead({
  titleTemplate: (titleChunk) => {
    return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
  },
})
</script>
```
::

现在，如果您在网站的另一个页面中使用 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head) 将标题设置为 `My Page`，浏览器标签页中显示的标题将是“My Page - Site Title”。您也可以传入 `null`，以默认显示“Site Title”。

### 模板参数

您可以使用 `templateParams` 在 `titleTemplate` 中提供除默认 `%s` 以外的额外占位符，从而更灵活地生成标题。

::code-group
```vue twoslash [useHead]
<script setup lang="ts">
useHead({
  titleTemplate: (titleChunk) => {
    return titleChunk ? `${titleChunk} %separator %siteName` : '%siteName'
  },
  templateParams: {
    siteName: 'Site Title',
    separator: '-',
  },
})
</script>
```
::

### Body 标签

对于适用的标签，您可以使用 `tagPosition: 'bodyClose'` 选项将它们添加到 `<body>` 标签的末尾。

例如：

```vue twoslash
<script setup lang="ts">
useHead({
  script: [
    {
      src: 'https://third-party-script.com',
      // 有效选项为: 'head' | 'bodyClose' | 'bodyOpen'
      tagPosition: 'bodyClose',
    },
  ],
})
</script>
```

## 示例

### 使用 `definePageMeta`

在 [`pages/` 目录](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/pages)中，您可以将 `definePageMeta` 与 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head) 配合使用，根据当前路由设置元数据。

例如，您可以先设置当前页面的标题（此标题通过宏在构建时提取，因此不能动态设置）：

```vue twoslash [pages/some-page.vue]
<script setup lang="ts">
definePageMeta({
  title: 'Some Page',
})
</script>
```

然后，在您的布局文件中，可以使用之前设置的路由元数据：

```vue twoslash [layouts/default.vue]
<script setup lang="ts">
const route = useRoute()

useHead({
  meta: [{ property: 'og:title', content: `App Name - ${route.meta.title}` }],
})
</script>
```

::link-example{to="https://nuxt.zhcndoc.com/docs/examples/features/meta-tags"}
::

::read-more{to="https://nuxt.zhcndoc.com/docs/3.x/directory-structure/pages/#page-metadata"}
::

### 动态标题

以下示例中，`titleTemplate` 可设置为带 `%s` 占位符的字符串，或者函数，使您能为 Nuxt 应用的每个路由动态设置页面标题：

```vue twoslash [app.vue]
<script setup lang="ts">
useHead({
  // 作为字符串，
  // `%s` 会被标题替代
  titleTemplate: '%s - Site Title',
})
</script>
```

```vue twoslash [app.vue]
<script setup lang="ts">
useHead({
  // 或作为函数
  titleTemplate: (productCategory) => {
    return productCategory
      ? `${productCategory} - Site Title`
      : 'Site Title'
  },
})
</script>
```

`nuxt.config` 也可以用作另一种设置页面标题的方式。但 `nuxt.config` 不支持动态标题，因此推荐在 `app.vue` 文件中使用 `titleTemplate` 添加动态标题，从而应用于 Nuxt 应用的所有路由。

### 外部 CSS

以下示例展示了如何通过 [`useHead`](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-head) 组合函数的 `link` 属性或使用 `<Link>` 组件来启用 Google Fonts：

::code-group
```vue twoslash [useHead]
<script setup lang="ts">
useHead({
  link: [
    {
      rel: 'preconnect',
      href: 'https://fonts.googleapis.com',
    },
    {
      rel: 'stylesheet',
      href: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap',
      crossorigin: '',
    },
  ],
})
</script>
```

```vue [Components]
<template>
  <div>
    <Link
      rel="preconnect"
      href="https://fonts.googleapis.com"
    />
    <Link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
      crossorigin=""
    />
  </div>
</template>
```
::


## Sitemap

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