Meta 标签
了解如何将 Nuxt 2 迁移到 Nuxt Bridge 新的 meta 标签。
如果需要使用 head
访问组件状态,则应迁移到使用 useHead
。
如果需要使用 Options 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 meta API,可以通过新的 useHead
可组合函数访问。
<script setup lang="ts">
useHead({
title: 'My Nuxt App',
})
</script>
我们建议除了
useHead
之外,不要使用原生的 Nuxt 2 head()
属性,因为它们可能会冲突。有关如何使用此可组合函数的更多信息,请参阅文档。
Options 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 应用程序,但无法访问组件实例。如果您的 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>