您正在浏览 Nuxt 2 文档。前往 Nuxt 3 文档, 或了解更多关于 Nuxt 2 长期支持

元标签和 SEO

Nuxt 提供了三种向应用程序添加元数据的方式:

  • 使用 nuxt.config.js 全局配置
  • 使用 head 作为对象本地配置
  • 使用 head 作为函数本地配置,以访问 data 和 computed 属性

全局配置

Nuxt 允许通过 nuxt.config.js 中的 head 属性定义应用程序的所有默认 <meta> 标签。可以轻松添加 SEO 的默认 title 和 description 标签、设置视口、添加 favicon。

nuxt.config.js
export default {
  head: {
    title: 'my website title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: 'my website description'
      }
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
  }
}
此配置将为所有页面设置相同的标题和描述。

本地配置

还可以通过在每个页面的 script 标签中设置 head 属性来添加页面特定的标题和元数据。

pages/index.vue
<script>
export default {
  head: {
    title: 'Home page',
    meta: [
      {
        hid: 'description',
        name: 'description',
        content: 'Home page description'
      }
    ],
  }
}
</script>
使用 head 作为对象,仅为首页设置 title 和 description 的示例。
pages/index.vue
<template>
  <h1>{{ title }}</h1>
</template>
<script>
  export default {
    data() {
      return {
        title: 'Home page'
      }
    },
    head() {
      return {
        title: this.title,
        meta: [
          {
            hid: 'description',
            name: 'description',
            content: 'Home page description'
          }
        ]
      }
    }
  }
</script>
使用 head 作为函数,仅为首页设置 title 和 description 的示例。使用函数可以访问 data 和 computed 属性。

Nuxt 使用 vue-meta 更新应用程序的 document head 和 meta 元素。

为避免使用子组件时元标签重复,请使用 hid 键为元数据提供唯一标识符,这样 vue-meta 就知道应该覆盖默认标签。

外部资源

要包含脚本和字体等外部资源,需要在 nuxt.config.js 中全局添加,或在 head 对象或函数中本地添加。

可以向每个资源传递可选的 body: true,将资源包含在 </body> 结束标签之前。

全局配置

nuxt.config.js
export default {
  head: {
    script: [
      {
        src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'
      }
    ],
    link: [
      {
        rel: 'stylesheet',
        href: 'https://fonts.googleapis.com/css?family=Roboto&display=swap'
      }
    ]
  }
}

本地配置

pages/index.vue
<template>
  <h1>About page with jQuery and Roboto font</h1>
</template>

<script>
  export default {
    head() {
      return {
        script: [
          {
            src:
              'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'
          }
        ],
        link: [
          {
            rel: 'stylesheet',
            href: 'https://fonts.googleapis.com/css?family=Roboto&display=swap'
          }
        ]
      }
    }
  }
</script>

<style scoped>
  h1 {
    font-family: Roboto, sans-serif;
  }
</style>
Edit this page on GitHub Updated at Tue, Apr 14, 2026