Vue.js 使用i18n和Nuxt时设置语言属性?
使用Nuxt,您可以在Nuxt.config.js文件中设置language HTML属性,如下所示:Vue.js 使用i18n和Nuxt时设置语言属性?,vue.js,internationalization,nuxt.js,vue-i18n,nuxt-i18n,Vue.js,Internationalization,Nuxt.js,Vue I18n,Nuxt I18n,使用Nuxt,您可以在Nuxt.config.js文件中设置language HTML属性,如下所示: module.exports = { head: { htmlAttrs: { lang: 'en-GB', }, ... etc etc 但是,如果您有一个多语言应用程序,您应该怎么做?有没有办法根据区域设置设置语言属性 我认为也许document.documentElement.setAttribute('lang','language code')可以工作,但是
module.exports = {
head: {
htmlAttrs: {
lang: 'en-GB',
},
... etc etc
但是,如果您有一个多语言应用程序,您应该怎么做?有没有办法根据区域设置设置语言属性
我认为也许document.documentElement.setAttribute('lang','language code')
可以工作,但是由于nuxt是在服务器端呈现的,它似乎无法访问documentElement对象
谢谢
{{$t(“hello”)}
注意:我没有测试代码可能我迟到了,但它与您的
布局/default.vue中的这段代码一样简单:
export default {
// other code...
head() {
return {
htmlAttrs: {
lang: this.$i18n.locale
}
}
},
// other code...
}
如果您使用的是nuxt-i18n,则可以在默认布局中使用addSeoAttributes:true
调用$nuxtI18nHead
。这将设置lang
属性以及一些其他特定于语言的标题属性,以实现更好的搜索引擎优化
导出默认值{
总目(){
返回此。$numsti18nhead({addSeoAttributes:true})
},
}
来源:谢谢,尽管我认为这实际上并没有在标记中设置语言属性。我这样问是因为这对屏幕阅读器等来说似乎很重要(Wave显示这是一个错误)。这不是OP要求的。你怎么能在nuxt.config.js中使用它呢?这对我不管用。您可以使用此选项。$i18n表示head,但head必须是一个返回对象的函数,而不仅仅是一个对象。正如@remino前面所说,$i18n
无法通过numxt.config.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')
}
})
}
module.exports = {
plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
head: {
htmlAttrs: {
lang: this.$i18n.locale,
}
}
}
{
"hello": "Hello World"
}
<p>{{ $t("hello") }}</p>
export default {
// other code...
head() {
return {
htmlAttrs: {
lang: this.$i18n.locale
}
}
},
// other code...
}