如何更改 i18n 默认添加的 head 元标记
og:description
内容值?
我知道我可以用 head 函数在每个页面中重写它,但我正在寻找更好的方法。
也许最好的方法是强制 i18n 用
og:description
标签内容值的值填充 description
内容值。
根据@doebi的方法,我想出了以下解决方案。
export default {
head() {
return this.headData
}
computed: {
headData() {
const t = this.$i18n.t
return {
title: t('thispages.title'),
meta: [
{
hid: 'description',
name: 'description',
content: t('thispages.description')
}
],
}
}
},
...
}
在具有组合 API 的 Nuxt 中,我们可以利用
useMeta
export default {
setup(){
const
{ t } = useI18n() // from 'vue-i18n'
useMeta({ // from '@nuxtjs/composition-api
title: t('thispages.title'),
meta: [
{
hid: 'description',
name: 'description',
content: t('thispages.description')
}
]
})
},
...
}
我也遇到了同样的问题,但找不到开箱即用的奇特方法。所以我想出了这个解决方案:
export default {
computed: {
locale() {
return this.$i18n.localeProperties.code;
}
},
head() {
const heads = {
'en': {
title: 'English Title',
meta: [
{
hid: 'description',
name: 'description',
content: 'Home page description'
}
],
},
'de': {
title: 'Deutscher Titel',
meta: [
{
hid: 'description',
name: 'description',
content: 'Home page description'
}
],
}
};
return heads[this.locale];
}
}
为您想要支持的所有语言创建一个对象
heads
,并让 head 函数根据 locale
变量返回正确的对象。我使用了计算属性,因为它也在模板中使用。
如果您希望每个页面上的
og:description
值相同,可以在 nuxt.config.js
或 /layout/default.vue
中设置。除非您在 /pages/yourPage.vue
中指定新值,否则每个页面上的标签值都相同。
在您的元数据中
nuxt.config.js
添加以下内容:
export default {
head: {
meta: [
{ hid: 'og:description', property: 'og:description' content: 'My own description' },
],
}
}
您可以对
og:title
等进行同样的操作
您可以使用 Nuxt 3 提供的
definePageMeta
函数来定义特定于页面的元数据,包括 Open Graph 标签。 useI18n
中的 nuxt-i18n
可组合项可用于访问本地化字符串。
首先,确保您已正确设置 i18n 插件,并在语言环境文件 145 中准备好描述的翻译。
以下是如何在页面组件中使用
definePageMeta
来设置 og:description
元标记的示例:
<script setup>
import { definePageMeta } from '#imports'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
definePageMeta({
head: {
meta: [
{
hid: 'og:description',
property: 'og:description',
content: t('descriptionKey') // Replace 'descriptionKey' with your actual i18n key
}
]
}
})
</script>
对于更完整的
<head>
解决方案,我强烈建议 unhead
,对于您的情况,有一个 useSeoMeta
可组合项。这个库也有一个 nuxt
集成指南。