元标签
了解如何从 Nuxt 2 迁移到 Nuxt Bridge 的新元标签。
如果你需要在组件中通过 head 访问状态,应该迁移到使用 useHead 。
如果你需要使用 Options API,当你使用 defineNuxtComponent 时,可以使用 head() 方法。
迁移指南
设置 bridge.meta
import { defineNuxtConfig } from '@nuxt/bridge'
export default defineNuxtConfig({
bridge: {
meta: true,
nitro: false // 如果已完成迁移到 Nitro,设置为 true
}
})
更新 head 属性
在你的 nuxt.config 中,将 head 重命名为 meta。(注意对象不再有用于去重的 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>
建议不要同时使用原生 Nuxt 2 的
head() 属性和 useHead ,它们可能会发生冲突。更多关于如何使用该组合式函数的信息,请参见 文档。
Options API
<script>
// 如果使用 Options API 的 `head` 方法,必须使用 `defineNuxtComponent`
export default defineNuxtComponent({
head (nuxtApp) {
// `head` 接收 nuxt 应用实例,但无法访问组件实例
return {
meta: [{
name: 'description',
content: 'This is my page description.'
}]
}
}
})
</script>
可能的破坏性变更:
head 接收的是 nuxt 应用实例,无法访问组件实例。如果你的 head 代码中尝试通过 this 或 this.$data 访问数据对象,需要迁移到 useHead 组合式函数。标题模板
如果你想使用函数(以获得完全控制),则不能在 nuxt.config 中设置,建议改为在 /layouts 目录中设置。
layouts/default.vue
<script setup lang="ts">
useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title';
}
})
</script>