Nuxt 3 提供多种不同的方式来管理你的元标签:
nuxt.config。useHead composable你可以自定义 title、titleTemplate、base、script、noscript、style、meta、link、htmlAttrs 和 bodyAttrs。
Unhead 来管理你的元标签,但实现细节可能会改变。nuxt.config 中,将 head 重命名为 meta。考虑将这份共享的元配置移到你的 app.vue 中。(注意对象不再有用于去重的 hid 键。)head 访问组件状态,应该迁移为使用 useHead。你也可以考虑使用内置的元组件。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 还提供了一些元组件,你可以使用它们来完成相同的任务。虽然这些组件看起来类似于 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>