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:
Install the Vue I18n Package: Start by installing the Vue I18n package. Open your terminal and run:
bashnpm install vue-i18n
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');
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.
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>
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.
Pluralization and Variables: Vue I18n supports pluralization and variable substitution. Refer to the documentation for details on how to handle these cases.