How to implement internationalization (i18n) in Vue.js



Image not found!!

Internationalization (i18n) in Vue.js involves setting up your application to support multiple languages and providing translations for various content. Here's a step-by-step guide on how to implement internationalization in Vue.js:

  1. Install the Vue I18n Package: Start by installing the Vue I18n package. Open your terminal and run:

    bash
    npm install vue-i18n
  2. Setup Vue I18n in Your Project: In your main Vue instance (usually main.js), set up Vue I18n:

    javascript
    // main.js import Vue from 'vue'; import VueI18n from 'vue-i18n'; Vue.use(VueI18n); const i18n = new VueI18n({ locale: 'en', // default locale messages: { en: require('./locales/en.json'), // import English translations // Add other languages as needed }, }); new Vue({ i18n, // ...other configurations }).$mount('#app');
  3. Create Language Files: Create language files for each supported language in the locales folder. For example, create en.json for English:

    json
    // en.json { "hello": "Hello", "greeting": "Welcome to our app" // ...other translations }

    Repeat this step for other languages, changing the file name accordingly.

  4. Usage in Components: Use the $t method or the {{ $t('key') }} syntax in your components to display translated content:

    html
    <!-- Example.vue --> <template> <div> <p>{{ $t('hello') }}</p> <p>{{ $t('greeting') }}</p> </div> </template> <script> export default { // ...component options } </script>
  5. Switching Languages: You can add a language switcher to allow users to change the language. Update the locale in your Vue instance to trigger a re-render with the new language.

  6. Pluralization and Variables: Vue I18n supports pluralization and variable substitution. Refer to the documentation for details on how to handle these cases.