Introduction: Vue I18n is an internationalization plugin of Vue.js. It easily integrates some localization features into your Vue.js Application.
You can introduce internationalization into your app with a simple API.
In addition to simple translation, support localization such as pluralization, number, datetime ... etc.
You can manage locale messages on a single file component.
Pre-requisite:
It is assumed that the basics of VueJS are already known including the folder structure and how the Vue app works
Getting started
Creating a global application with Vue + Vue I18n is dead simple. With Vue.js, we are already composing our application with components. When adding Vue I18n to the mix, all we need to do is ready resource messages and simply use the localization API that is offered with Vue I18n.
Here’s a basic example via script tag:
Installation
For Installation need to run the below comment
npm install vue-i18
When using with a module system, you must explicitly install the vue-i18n via app.use():
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
// something vue-i18n options here ...
})
const app = createApp({
// something vue options here ...
})
app.use(i18n)
app.mount('#app')
HTML
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-i18n@9"></script>
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
In the HTML template, we use the $t translation API injected with Vue I18n, to localize. This allows Vue I18n to change the locale without rewriting the template, and also to be able to support the global application.
JavaScript
// 1. Readily translated locale messages
// The structure of the locale message is the hierarchical object structure with each locale as the top property
const messages = {
en: {
message: {
hello: 'Hello world'
}
},
ja: {
message: {
hello: 'こんにちは、世界'
}
}
}
// 2. Create an i18n instance with options
const i18n = VueI18n.createI18n({
locale: 'ja', // set locale
fallbackLocale: 'en', // set fallback locale
messages, // set locale messages
// If you need to specify other options, you can set other options
// ...
})
// 3. Create a Vue root instance
const app = Vue.createApp({
// set something options
// ...
})
// 4. Install i18n instance to make the whole app i18n-aware
app.use(i18n)
// 5. Mount
app.mount('#app')
// Now the app has started!
The following will be the output:
<div id="app">
<p>こんにちは、世界</p>
</div>