How to translate your Vue.js 3 application with vue i18n
- User
How to translate your Vue.js 3 application with vue i18n
- Assistant
How to translate your Vue.js 3 application with vue i18n
Translating a Vue.js 3 application using vue-i18n is a straightforward process. Below are the steps you need to follow to set up internationalization (i18n) in your Vue.js 3 application.
vue-i18nFirst, you need to install vue-i18n if you haven't already.
npm install vue-i18n@next
Organize your translation strings into separate language files. For example, you can create a folder named locales and add files like en.json and fr.json.
src/locales/en.json:
{
"welcome": "Welcome to our application",
"goodbye": "Goodbye",
"info": {
"description": "This is an example of how to use Vue I18n."
}
}
src/locales/fr.json:
{
"welcome": "Bienvenue dans notre application",
"goodbye": "Au revoir",
"info": {
"description": "Ceci est un exemple de l'utilisation de Vue I18n."
}
}
vue-i18nYou can now set up vue-i18n in your main application file (usually main.js).
src/main.js:
import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import App from './App.vue';
import en from './locales/en.json';
import fr from './locales/fr.json';
const messages = {
en: en,
fr: fr,
};
const i18n = createI18n({
locale: 'en', // set locale
fallbackLocale: 'en', // set fallback locale
messages, // set locale messages
});
const app = createApp(App);
app.use(i18n);
app.mount('#app');
You can now start using the translations in your components with the $t method.
src/components/HelloWorld.vue:
<template>
<div>
<h1>{{ $t("welcome") }}</h1>
<p>{{ $t("info.description") }}</p>
<button @click="changeLanguage('fr')">French</button>
<button @click="changeLanguage('en')">English</button>
<p>{{ $t("goodbye") }}</p>
</div>
</template>
<script>
export default {
methods: {
changeLanguage(lang) {
this.$i18n.locale = lang;
},
},
};
</script>
Now you can run your Vue.js application:
npm run serve
Here are some additional features and tips you might find useful:
Dynamic Language Switching - As shown in the example, you can change the language by updating the locale.
Component Translations - You can use the v-t directive to translate directly in your templates:
<h1 v-t="'welcome'"></h1>
Pluralization and Interpolation - vue-i18n supports pluralization and interpolation, which can be used in your language files.
Example for pluralization:
{
"count": "{count} item | {count} items"
}
Nested Messages - Keep your translation strings organized using nested keys.
Date and Number Formatting - You can also format dates and numbers according to the locale.
By following these steps, you should now have a Vue.js 3 application that supports multiple languages using vue-i18n. Make sure to customize the language files to suit your application's texts and needs.