Meta 標籤
管理你的 meta 標籤,從 Nuxt 2 到 Nuxt 3。
Nuxt 3 提供了幾種不同的方式來管理你的 meta 標籤
- 透過你的
nuxt.config
。 - 透過
useHead
可組合項 - 透過 全域性 meta 元件
你可以自定義 title
、titleTemplate
、base
、script
、noscript
、style
、meta
、link
、htmlAttrs
和 bodyAttrs
。
Nuxt 當前使用
Unhead
來管理你的 meta 標籤,但實現細節可能會改變。遷移
- 在你的
nuxt.config
中,將head
重新命名為meta
。考慮將此共享 meta 配置移至你的app.vue
中。(請注意,物件不再具有用於去重功能的hid
鍵。) - 如果你需要使用
head
訪問元件狀態,你應該遷移到使用useHead
。你也可以考慮使用內建的 meta 元件。 - 如果你需要使用 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>
Meta 元件
Nuxt 3 還提供了 meta 元件,你可以使用它們來完成相同的任務。雖然這些元件看起來與 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>