How to Create Multilingual App in Vue.js

Introduction

Creating a multilingual app in Vue.js involves managing translations for different languages and dynamically switching between them based on user preferences. Here's a general guide on how to achieve this.

1. Install Dependencies

Install a package to handle translations. One popular choice is vue-i18n.

npm install vue-i18n

2. Set Up Translation Files

Create translation files for each language you want to support. For example, create a locales directory with separate files for each language.

src
|-- locales
|   |-- en.json  // English translations
|   |-- es.json  // Spanish translations

In each file, define translations for the same keys.

en.json

{
  "greeting": "Hello!",
  "message": "Welcome to my app."
}

es.json

{
  "greeting": "¡Hola!",
  "message": "Bienvenido a mi aplicación."
}

3. Configure vue-i18n

In your main Vue.js file (e.g., main.js), configure vue-i18n and set the initial language.

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

const messages = {
  en: require('./locales/en.json'),
  es: require('./locales/es.json')
};

const i18n = new VueI18n({
  locale: 'en', // initial locale
  messages
});

new Vue({
  el: '#app',
  i18n,
  // ... other configurations
});

4. Use Translations in Components

Use the $t method to access translations in your components.

<template>
  <div>
    <p>{{ $t('greeting') }}</p>
    <p>{{ $t('message') }}</p>
  </div>
</template>

5. Implement Language Switching

Create a method to dynamically change the language.

methods: {
  changeLanguage(locale) {
    this.$i18n.locale = locale;
  }
}

6. Add Language Switching UI

Add a language switcher in your components or navigation.

<template>
  <div>
    <button @click="changeLanguage('en')">English</button>
    <button @click="changeLanguage('es')">Español</button>
  </div>
</template>

7. Dynamic Components

If your app has dynamic content (e.g., content loaded from an API), make sure to update the translations whenever the content changes.

8. Handle Pluralization and Variables

vue-i18n supports pluralization and variable substitution. Refer to the documentation for details on these features.

Additional Considerations

  • Persisting User Preferences: You might want to persist the user's language preference (e.g., using cookies or local storage) so that it's remembered across sessions.
  • SEO Considerations: If you have multilingual content, consider implementing SEO best practices, such as using hreflang tags in your HTML.

Conclusion

This is a basic guide to get you started. For more detailed information and advanced usage, refer to the official documentation of vue-i18n.