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>