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
重新命名為 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' }
]
}
}
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
目錄中設定。
layouts/default.vue
<script setup lang="ts">
useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title';
}
})
</script>