To install vue-i18n, use the following command:
npm install vue-i18n
Add the plugin to nuxt.config.js file:
plugins: ['~/plugins/i18n.js']
Create a new file named plugins/i18n.js and add the following code:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
'en': require('~/locales/en.json'),
'fr': require('~/locales/fr.json')
}
})
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}
In your store index.js file, include the following code:
export const state = () => ({
locales: ['en', 'fr'],
locale: 'en'
})
export const mutations = {
SET_LANG (state, locale) {
if (state.locales.includes(locale)) {
state.locale = locale
}
}
}
Create locals/en.json file with the following content:
{
"links": {
"home": "Home",
"about": "About",
"english": "English version",
"french": "French version"
},
"home": {
"title": "Welcome",
"introduction": "This is an introduction in English."
},
"about": {
"title": "About",
"introduction": "This page is made to give you more information."
}
}
Create locals/fr.json file with the following content:
{
"links": {
"home": "Accueil",
"about": "À propos",
"english": "Version Anglaise",
"french": "Version Française"
},
"home": {
"title": "Bienvenue",
"introduction": "Ceci est un texte d'introduction en Français."
},
"about": {
"title": "À propos",
"introduction": "Cette page est faite pour vous donner plus d'informations."
}
}
Now, you can use i18n in your index.vue file:
<template>
<div class="Content">
<div class="container">
<h1 class="Content__Title">
{{ $t('home.title') }}
</h1>
<p>{{ $t('home.introduction') }}</p>
</div>
</div>
</template>
<script>
export default {
}
</script>