メタタグ
Nuxt 2 から Nuxt 3 まで、メタタグを管理します。
Nuxt 3 は、メタタグを管理するためのいくつかの異なる方法を提供します
nuxt.configを通じて。useHeadコンポーザブルを通じて- グローバルメタコンポーネントを通じて
title、titleTemplate、base、script、noscript、style、meta、link、htmlAttrs、bodyAttrs をカスタマイズできます。
現在 Nuxt は
Unheadを使用してメタタグを管理していますが、実装の詳細は変更される可能性があります。移行
nuxt.configで、headをmetaに変更します。この共有メタ設定をapp.vueに移動することを検討してください。(オブジェクトには重複排除のためのhidキーがなくなったことに注意してください)headでコンポーネントの状態にアクセスする必要がある場合は、useHeadを使用するように移行する必要があります。組み込みのメタコンポーネントを使用することも検討できます。- 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>
<script setup lang="ts">
const title = ref('My App')
const description = ref('My App Description')
// This will be reactive when you change title/description above
useHead({
title,
meta: [{
name: 'description',
content: description,
}],
})
</script>
メタコンポーネント
Nuxt 3 は、同じタスクを達成するために使用できるメタコンポーネントも提供します。これらのコンポーネントは HTML タグと似ていますが、Nuxt によって提供され、同様の機能を持っています。
<script>
export default {
head () {
return {
title: 'My App',
meta: [{
hid: 'description',
name: 'description',
content: 'My App Description',
}],
}
},
}
</script>
<template>
<div>
<Head>
<Title>My App</Title>
<Meta
name="description"
content="My app description"
/>
</Head>
<!-- -->
</div>
</template>
- これらのコンポーネント名をネイティブ HTML 要素 (
<title>ではなく<Title>) と区別するために、大文字を使用してください。 - これらのコンポーネントは、ページのテンプレート内のどこにでも配置できます。
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>