Localization helps you manage the multi-language system for static content with a simple function $t(‘key’). This article will show you how to set it up with the vue-i18n package. Also, make it more manageable by separating the localization of each JSON file by module.
Install the package
Install the vue-i18n package version for Vue 2.
npm install vue-i18n@8
Setup i18n localization
The localizations structure will have a folder wrap named by languages (en, kh) and each of the folders can have many JSON files.
In your /src folder, create the locales folder and en, kh subfolder with the sample.json file in each subfolder en, kh.
/src /locales /en sample.json /kh sample.json
In /src/locales/en/sample.json
{
"title": "Localization sample",
"welcome": "Welcome"
}
In /src/locales/kh/sample.json
{
"title": "គំរូ",
"welcome": "សូមស្វាគមន៍"
}
Create an i18n plugin to load localizations message from our locales file to Vue. In your /src folder create an i18n.js file.
In /src/i18n.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
function loadLocaleMessages() {
const locales = require.context('@/locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
const messages = {};
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1) {
const matched = key.match(/([A-Za-z0-9-_]+)\//i);
const matchedModule = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1 && matched && matchedModule.length > 1) {
const locale = matched[1];
const module = matchedModule[1];
if (!messages[locale]) messages[locale] = {};
messages[locale][module] = locales(key);
}
}
});
return messages;
}
const i18n = new VueI18n({
locale: 'en', // set locale
messages: loadLocaleMessages(), // set locale messages
});
export default i18n;
Note: You can change language static or dynamic by changing the locale (en, kh).
In your /src/main.js
Tell Vue to use the i18n plugin.
import Vue from 'vue';
import App from './App.vue';
import router from './routes';
import i18n from './i18n';
Vue.config.productionTip = false;
new Vue({
router,
i18n,
render: h => h(App)
}).$mount('#app')
Usage
In any Vue file call with the function $t. ($t(‘folderName.jsonKey’))
<template>
<div>
<h3>
{{ $t('sample.title') }}
</h3>
<p>
{{ $t('sample.welcome') }}
</p>
</div>
</template>
<script>
export default {
}
</script>
Wrapping up
The vue-i18n package provides you with the best way to work with localizations with a simple easy-to-use setup. See more at https://kazupon.github.io/vue-i18n/.