使用Nuxt,您可以在 nuxt.config.js 文件中设置语言HTML属性,如下所示:
module.exports = {
head: {
htmlAttrs: {
lang: 'en-GB',
},
... etc etc
但是,如果您有多语言应用,该怎么办?有没有办法根据语言环境设置语言属性?
我认为document.documentElement.setSttribute('lang', 'language-code')
可能会起作用,但是当nuxt呈现在服务器端时,它似乎无法访问documentElement对象。
由于
答案 0 :(得分:1)
也许我来晚了,但这就像您的layouts/default.vue
中的这段代码一样简单:
export default {
// other code...
head() {
return {
htmlAttrs: {
lang: this.$i18n.locale
}
}
},
// other code...
}
答案 1 :(得分:0)
- 安装vue-i18n npm
醇>
npm install vue-i18n
- 在插件目录中创建一个插件并添加以下代码。例如:i18n.js
醇>
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({app}) => {
app.i18n = new ueI18n({
locate: 'ja',
fallbackLocale: 'en',
silentTranslationWarn: true,
message: {
'ja': require('~/locale/ja/translations.json'),
'en': require('~/locale/en/translations.json')
}
})
}
- 在nuxt.config.js文件中包含此插件并设置lang
醇>
module.exports = {
plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
head: {
htmlAttrs: {
lang: this.$i18n.locale,
}
}
}
- translations.json文件包含您的json格式的翻译
醇>
{
"hello": "Hello World"
}
- 在组件文件中,您可以访问以下翻译
醇>
<p>{{ $t("hello") }}</p>
注意:我没有测试代码
答案 2 :(得分:0)
如果您使用的是 nuxt-i18n,则可以在默认布局中使用 $nuxtI18nHead
调用 addSeoAttributes: true
。这将设置 lang
属性以及其他一些特定于语言的标题属性,以实现更好的 SEO。
export default {
head() {
return this.$nuxtI18nHead({ addSeoAttributes: true })
},
}