Meta 標籤

管理你的 meta 標籤,從 Nuxt 2 到 Nuxt 3。

Nuxt 3 提供了幾種不同的方式來管理你的 meta 標籤

  1. 透過你的 nuxt.config
  2. 透過 useHead 可組合項
  3. 透過 全域性 meta 元件

你可以自定義 titletitleTemplatebasescriptnoscriptstylemetalinkhtmlAttrsbodyAttrs

Nuxt 當前使用Unhead來管理你的 meta 標籤,但實現細節可能會改變。
文件 > 4 X > 入門 > Seo Meta中閱讀更多內容。

遷移

  1. 在你的 nuxt.config 中,將 head 重新命名為 meta。考慮將此共享 meta 配置移至你的 app.vue 中。(請注意,物件不再具有用於去重功能的 hid 鍵。)
  2. 如果你需要使用 head 訪問元件狀態,你應該遷移到使用 useHead。你也可以考慮使用內建的 meta 元件。
  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>

Meta 元件

Nuxt 3 還提供了 meta 元件,你可以使用它們來完成相同的任務。雖然這些元件看起來與 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. 你可以將這些元件放置在頁面模板的任何位置。

Options 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>