元标签
了解如何从 Nuxt 2 迁移到 Nuxt Bridge 的新 meta 标签。
如果你需要在 head 中访问组件状态,应该迁移为使用 useHead。
如果你需要使用选项式 API,在使用 defineNuxtComponent 时可以使用 head() 方法。
迁移
设置 bridge.meta
import { defineNuxtConfig } from '@nuxt/bridge'
export default defineNuxtConfig({
bridge: {
meta: true,
nitro: false, // If migration to Nitro is complete, set to true
},
})
更新 head 属性
在你的 nuxt.config 中,将 head 重命名为 app.head。(注意对象不再具有用于去重的 hid 键。)
export default {
head: {
titleTemplate: '%s - Nuxt',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Meta description' },
],
},
}
export default defineNuxtConfig({
app: {
head: {
titleTemplate: '%s - Nuxt',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'description', content: 'Meta description' },
],
},
},
})
useHead 组合式函数
Nuxt Bridge 提供了一个新的 Nuxt 3 元信息 API,可以通过新的 useHead 组合式函数访问。
<script setup lang="ts">
useHead({
title: 'My Nuxt App',
})
</script>
我们建议不要在使用
useHead 的同时再使用原生 Nuxt 2 的 head() 属性,因为它们可能会冲突。有关如何使用此组合式函数的更多信息,请参阅 文档。
选项式 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>
可能的破坏性更改:
head 会接收 nuxt app,但无法访问组件实例。如果你在 head 中的代码尝试通过 this 或 this.$data 访问数据对象,则需要迁移到 useHead 组合式函数。标题模板
如果你想使用一个函数(以获得完全控制),则不能在 nuxt.config 中设置,建议改为在 /layouts 目录中设置。
app/layouts/default.vue
<script setup lang="ts">
useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
},
})
</script>