Vue.js Internationalization (i18n)

Internationalization (often abbreviated as i18n) is the process of designing an application so that it can be adapted to various languages and regions without requiring engineering changes. In the context of Vue.js, i18n involves translating your application’s text, handling different date and number formats, and making sure your application can cater to users from different cultural backgrounds. This chapter will take you from the basics to advanced topics in Vue.js internationalization, ensuring you have a thorough understanding of how to make your Vue.js applications accessible to a global audience.

Basics of Internationalization

What is Internationalization?

Internationalization is the preparation of software so that it can support different languages and regions. It involves:

  • Localization: Adapting the software to meet the language, cultural, and other requirements of a specific region or market.
  • Translation: Converting the text from one language to another.
  • Formatting: Adjusting dates, numbers, and currencies to match local conventions.

Why Internationalize?

  • Reach a Global Audience: Make your application usable by people all around the world.
  • Improve User Experience: Provide a seamless experience for users in their native language.
  • Legal Requirements: Some regions have legal requirements for supporting multiple languages.

Setting Up Vue I18n

Installing Vue I18n

Vue I18n is the official internationalization library for Vue.js. To get started, install Vue I18n via npm:

				
					npm install vue-i18n@next

				
			

Basic Setup

Create an instance of Vue I18n and configure it in your Vue application. Here’s a simple setup:

				
					import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import App from './App.vue';

// Define messages
const messages = {
  en: {
    welcome: 'Welcome'
  },
  fr: {
    welcome: 'Bienvenue'
  }
};

// Create i18n instance with options
const i18n = createI18n({
  locale: 'en', // set locale
  fallbackLocale: 'en', // set fallback locale
  messages, // set locale messages
});

// Create Vue app
const app = createApp(App);
app.use(i18n);
app.mount('#app');

				
			

In this example, we define messages for English (en) and French (fr). We create an i18n instance with these messages and configure the default locale as English.

Using Translations in Components

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

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

				
			

This will display “Welcome” or “Bienvenue” depending on the current locale.

Advanced Configuration

Locale Switching

Allow users to switch between languages dynamically:

				
					<template>
  <div>
    <select v-model="locale" @change="changeLocale">
      <option value="en">English</option>
      <option value="fr">Français</option>
    </select>
    <p>{{ $t('welcome') }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{locale:'en'}},methods:{changeLocale(){this.$i18n.locale=this.locale}}}</script> 
				
			

This example adds a dropdown for language selection. When the user selects a language, the changeLocale method updates the current locale.

Handling Pluralization

Vue I18n supports pluralization, which allows you to handle singular and plural forms of words:

				
					const messages = {
  en: {
    apples: 'No apples | One apple | {count} apples'
  },
  fr: {
    apples: "Pas de pommes | Une pomme | {count} pommes"
  }
};

				
			

Use the $tc method for pluralization:

				
					<template>
  <div>
    <p>{{ $tc('apples', 0) }}</p>
    <p>{{ $tc('apples', 1) }}</p>
    <p>{{ $tc('apples', 5, { count: 5 }) }}</p>
  </div>
</template>

				
			

This will display the appropriate message based on the count.

Formatting Dates and Numbers

Date Formatting

Vue I18n can format dates according to the locale settings:

				
					const messages = {
  en: {
    date: '{date, date, short}'
  },
  fr: {
    date: '{date, date, short}'
  }
};

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages,
  datetimeFormats: {
    en: {
      short: {
        year: 'numeric', month: 'short', day: 'numeric'
      }
    },
    fr: {
      short: {
        year: 'numeric', month: 'short', day: 'numeric'
      }
    }
  }
});

				
			

In your component:

				
					<template>
  <div>
    <p>{{ $d(new Date(), 'short') }}</p>
  </div>
</template>

				
			

This will format the date according to the locale.

Number Formatting

Similarly, Vue I18n can format numbers and currencies:

				
					const messages = {
  en: {
    currency: '{amount, number, currency}'
  },
  fr: {
    currency: '{amount, number, currency}'
  }
};

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages,
  numberFormats: {
    en: {
      currency: {
        style: 'currency', currency: 'USD'
      }
    },
    fr: {
      currency: {
        style: 'currency', currency: 'EUR'
      }
    }
  }
});

				
			

In your component:

				
					<template>
  <div>
    <p>{{ $n(1000, 'currency') }}</p>
  </div>
</template>

				
			

This will format the number as currency according to the locale.

Message Syntax and Interpolation

Named Placeholders

Use named placeholders for dynamic content:

				
					const messages = {
  en: {
    greeting: 'Hello, {name}!'
  },
  fr: {
    greeting: 'Bonjour, {name}!'
  }
};

				
			

In your component:

				
					<template>
  <div>
    <p>{{ $t('greeting', { name: 'John' }) }}</p>
  </div>
</template>

				
			

This will output “Hello, John!” or “Bonjour, John!” based on the locale.

HTML Content

If your translations contain HTML, use the v-html directive:

				
					const messages = {
  en: {
    welcome: '<strong>Welcome</strong> to our site!'
  },
  fr: {
    welcome: '<strong>Bienvenue</strong> sur notre site!'
  }
};

				
			

In your component:

				
					<template>
  <div v-html="$t('welcome')"></div>
</template>

				
			

Testing and Debugging

Testing Translations

Ensure that translations are accurate and contextually correct. Use unit tests to verify translations:

				
					import { createI18n } from 'vue-i18n';
import { mount } from '@vue/test-utils';
import App from '@/App.vue';

const messages = {
  en: { welcome: 'Welcome' },
  fr: { welcome: 'Bienvenue' }
};

test('renders welcome message in English', () => {
  const i18n = createI18n({ locale: 'en', messages });
  const wrapper = mount(App, { global: { plugins: [i18n] } });
  expect(wrapper.text()).toContain('Welcome');
});

test('renders welcome message in French', () => {
  const i18n = createI18n({ locale: 'fr', messages });
  const wrapper = mount(App, { global: { plugins: [i18n] } });
  expect(wrapper.text()).toContain('Bienvenue');
});

				
			

Debugging i18n Issues

Use Vue DevTools and console logging to debug issues with internationalization. Ensure that locale messages are loaded correctly and that the current locale is set properly.

Internationalization is a critical aspect of modern web applications, enabling you to reach a global audience and provide a better user experience. Vue I18n offers a comprehensive set of tools to handle translations, formatting, and locale management in Vue.js applications. By following the practices outlined in this chapter, you can ensure that your Vue.js application is fully internationalized and ready to cater to users from different linguistic and cultural backgrounds. Happy coding !❤️

Table of Contents