Introduction to Internationalization (i18n)

Internationalization (i18n) is a vital aspect of developing web applications for a global audience. In Vue.js, the i18n library allows you to create multi-language apps by providing translations for various languages. In this guide, we'll explore how to implement i18n in Vue.js to make your app accessible to users from different language backgrounds.


Installing Vue I18n

To use i18n in your Vue.js project, you need to install the Vue I18n library. You can do this using npm or yarn. Here's an example of installing Vue I18n with npm:


# Install Vue I18n
npm install vue-i18n

After installing Vue I18n, you can set it up in your Vue application.


Configuring Vue I18n

To configure Vue I18n, you need to create a plugin and define your language translations. Here's a basic example:


// Import Vue and Vue I18n
import Vue from 'vue';
import VueI18n from 'vue-i18n';
// Use Vue I18n
Vue.use(VueI18n);
// Create a new instance of Vue I18n
const i18n = new VueI18n({
locale: 'en', // Default language
messages: {
en: {
greeting: 'Hello, Vue!',
},
es: {
greeting: '¡Hola, Vue!',
},
fr: {
greeting: 'Bonjour, Vue!',
},
},
});
// Export the i18n instance for use in your Vue components
export default i18n;

In this example, we've defined translations for English, Spanish, and French. The `i18n` instance is then exported for use in Vue components.


Using Translations in Vue Components

Once you've configured i18n, you can use translations in your Vue components. Here's an example of displaying a greeting message in multiple languages:


<template>
<div>
<p>{{ $t('greeting') }}</p>
</div>
</template>
<script>
export default {
// ...
};
</script>

The `$t` function is used to access translations in your Vue components. It will display the greeting message in the selected language.


Switching Languages

To allow users to switch between languages, you can create a language picker component and set the active locale in your app. Here's a simplified example:


<template>
<div>
<button @click="changeLanguage('en')">English</button>
<button @click="changeLanguage('es')">Spanish</button>
<button @click="changeLanguage('fr')">French</button>
</div>
</template>
<script>
export default {
methods: {
changeLanguage(locale) {
this.$i18n.locale = locale;
},
},
};
</script>

In this example, clicking the language buttons changes the active locale, which updates the displayed translations.


Conclusion

Vue.js Internationalization (i18n) is a powerful tool for creating multi-language apps. By configuring Vue I18n, defining translations, and using the `$t` function in your components, you can make your Vue application accessible to a diverse global audience.