Easily setup nuxt internationalization with vue-i18n
Published in
2 min readJun 17, 2019
#nuxt #nuxtjs #i18n #code4mk.
# vue-i18n
vue-i18n is best intertionalization plugin for vue project.
# how add vue-i18n inside nuxt
Nuxt.js link up package by plugin system. create a plugin then add that inside nuxt.config.js
# create plugin
~ plugins/i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'Vue.use(VueI18n)export default ({ app, store}) => {
app.i18n = new VueI18n({
locale: 'en',
fallbackLocale: 'en',
silentTranslationWarn: true,
messages: {
'bn': {
'menu':{
'home': 'হোম',
'blog': 'ব্লগ',
'contact': 'যোগাযোগ'
},
},
'en': {
"menu": {
'home': 'home',
'blog': 'blog',
'contact': 'contact'
},
},
},
}
})//app.i18n.locale = 'bn' app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}
# plugin add in nuxt config
plugins: [
'~/plugins/i18n.js'
]
# nuxt page
<template><div class><ul><li class="my-list">{{$t("menu.home")}}</li><li class="my-list">{{$t("menu.blog")}}</li><li class="my-list">{{$t("menu.contact")}}</li><li><select v-model="$i18n.locale" @change="lang($i18n.locale)"><option v-for="(lang, i) in $i18n.availableLocales" :key="`Lang${i}`" :value="lang">{{ lang }}</option></select></li></ul></div></template><script>export default {created: function() {if (process.browser) {if (localStorage.getItem("lang")) {if (this.$route.query.lang) {this.$i18n.locale = this.$route.query.lang;} else {this.$i18n.locale = localStorage.getItem("lang");}}}},methods: {lang: function(l) {this.$router.push({query: {lang: l}});this.$i18n.locale = l;if (process.browser) {localStorage.setItem("lang", l);}}}};</script><style lang="css" scoped >ul {list-style: none;display: block;}ul li {display: inline-block;}.my-list {color: blue;cursor: pointer;}</style>
# demo