Nuxt 3 提供了几种不同的方式来管理您的 meta 标签
nuxt.config。useHead 组合式函数您可以自定义 title、titleTemplate、base、script、noscript、style、meta、link、htmlAttrs 和 bodyAttrs。
Unhead来管理您的 meta 标签,但实现细节可能会有所变化。nuxt.config 中,将 head 重命名为 meta。考虑将此共享 meta 配置移至您的 app.vue 中。(请注意,对象不再具有用于去重 的 hid 键。)head 访问组件状态,您应该迁移到使用 useHead。您也可以考虑使用内置的 meta 组件。defineNuxtComponent 时,可以使用 head() 方法。<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 还提供了 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>
<Title> 而不是 <title>)。<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>