Meta 标签
了解如何从 Nuxt 2 迁移到 Nuxt Bridge 的新 meta 标签。
如果你需要使用组件状态来操作 head,你应该迁移到使用 useHead。
如果你需要使用 Options API,有一个 head() 方法可在使用 defineNuxtComponent 时使用。
迁移
设置 bridge.meta
import { defineNuxtConfig } from '@nuxt/bridge'
export default defineNuxtConfig({
bridge: {
meta: true,
nitro: false, // 如果向 Nitro 的迁移已完成,设置为 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 兼容的 meta API,可以通过新的 useHead 组合式函数访问。
<script setup lang="ts">
useHead({
title: 'My Nuxt App',
})
</script>
这个
useHead 组合式函数在底层使用 @unhead/vue(而不是 vue-meta)来操作你的 <head>。
::我们建议不要同时使用原生的 Nuxt 2
head() 属性和 useHead,因为它们可能会冲突。
::有关如何使用这个组合式函数的更多信息,请参阅文档。Options API
<script>
// 如果使用 options API 的 `head` 方法,你必须使用 `defineNuxtComponent`
export default defineNuxtComponent({
head (nuxtApp) {
// `head` 接收 nuxt app,但无法访问组件实例
return {
meta: [{
name: 'description',
content: 'This is my page description.',
}],
}
},
})
</script>
可能的破坏性更改:
head 接收 nuxt app,但无法访问组件实例。如果你的 head 中的代码试图通过 this 或 this.$data 访问 data 对象,你将需要迁移到 useHead 组合式函数。
::标题模板
如果你想使用一个函数(以获得完全控制),那么这不能在你的 nuxt.config 中设置,建议改为在你的/layouts 目录中设置。app/layouts/default.vue
<script setup lang="ts">
useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
},
})
</script>