Reputation: 28059
With Nuxt, you can set the language HTML attribute inside the nuxt.config.js file like so:
module.exports = {
head: {
htmlAttrs: {
lang: 'en-GB',
},
... etc etc
However, what should you do if you have a multi-language app? Is there any way to set the language attribute based on the locale?
I thought that maybe document.documentElement.setSttribute('lang', 'language-code')
would work, but as nuxt is rendered server side, it doesn't seem to have access to the documentElement object.
Thanks
Upvotes: 7
Views: 13195
Reputation: 81
If you're using nuxt-i18n, you can call $nuxtI18nHead
with addSeoAttributes: true
in your default layout. This will set the lang
attribute as well as some other language-specific header attributes for better SEO.
export default {
head() {
return this.$nuxtI18nHead({ addSeoAttributes: true })
},
}
Source: https://i18n.nuxtjs.org/seo#improving-performance
Upvotes: 3
Reputation: 422
Maybe I'm late, but it's just as simple as this chunk of code in your layouts/default.vue
:
export default {
// other code...
head() {
return {
htmlAttrs: {
lang: this.$i18n.locale
}
}
},
// other code...
}
Upvotes: 14
Reputation: 1191
- Install vue-i18n npm
npm install vue-i18n
- create a plugin in the plugin dir and add the below code. Eg: 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')
}
})
}
- Include this plugin in your nuxt.config.js file and set the lang
module.exports = {
plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
head: {
htmlAttrs: {
lang: this.$i18n.locale,
}
}
}
- translations.json file contain your translation in json format
{
"hello": "Hello World"
}
- In component file, you can access the translation as below
<p>{{ $t("hello") }}</p>
Note: I didnt tested the code
Upvotes: 2