元标签

管理你的元标签,从 Nuxt 2 到 Nuxt 3。

Nuxt 3 提供多种不同的方式来管理你的元标签:

  1. 通过你的 nuxt.config
  2. 通过 useHead composable
  3. 通过 全局元组件

你可以自定义 titletitleTemplatebasescriptnoscriptstylemetalinkhtmlAttrsbodyAttrs

Nuxt 当前使用 Unhead 来管理你的元标签,但实现细节可能会改变。
Read more in Docs > 4 X > Getting Started > Seo Meta.

迁移

  1. 在你的 nuxt.config 中,将 head 重命名为 meta。考虑将这份共享的元配置移到你的 app.vue 中。(注意对象不再有用于去重的 hid 键。)
  2. 如果你需要使用 head 访问组件状态,应该迁移为使用 useHead。你也可以考虑使用内置的元组件。
  3. 如果你需要使用 Options API,当你使用 defineNuxtComponent 时,可以使用 head() 方法。

useHead

<script>
export default {
  data: () => ({
    title: 'My App',
    description: 'My App Description',
  }),
  head () {
    return {
      title: this.title,
      meta: [{
        hid: 'description',
        name: 'description',
        content: this.description,
      }],
    }
  },
}
</script>

元组件

Nuxt 3 还提供了一些元组件,你可以使用它们来完成相同的任务。虽然这些组件看起来类似于 HTML 标签,但它们由 Nuxt 提供并具有相似的功能。

<script>
export default {
  head () {
    return {
      title: 'My App',
      meta: [{
        hid: 'description',
        name: 'description',
        content: 'My App Description',
      }],
    }
  },
}
</script>
  1. 确保你对这些组件名称使用大写字母以将它们与原生 HTML 元素区分开(使用 <Title> 而不是 <title>)。
  2. 你可以将这些组件放在页面模板中的任何位置。

选项式 API

Nuxt 3 (Options API)
<script>
// if using options API `head` method you must use `defineNuxtComponent`
export default defineNuxtComponent({
  head (nuxtApp) {
    // `head` receives the nuxt app but cannot access the component instance
    return {
      meta: [{
        name: 'description',
        content: 'This is my page description.',
      }],
    }
  },
})
</script>