Internationalization with vue-i18n (Part 1)
This is part 1of a series on internalization with vue-i18n. Find part 2 here.
This tutorial will show you how to use the module vue-i18n to handle internalization in your Vue app.
Installation
Assuming you already have a Vue project set up, install vue-i18n using npm.
$ npm install vue-i18n
After that, you need to enable the plugin in your main app file (main.js).
import Vue from 'vue'
import App from './App'
import router from './router'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)Vue.config.productionTip = false/* eslint-disable no-new */new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
Usage
Now you need to setup your local messages in the same file.
const messages = {
en: {
message: {
hello: 'hello world'
}
},
fr: {
message: {
hello: 'Bonjour monde'
}
}
}
And create a vueI18n instance:
const i18n = new VueI18n({
locale: 'fr', // set locale
messages // set locale messages
})
Your i18n instance will then be added to your project vue instance:
new Vue({
i18n,
el: '#app',
template: '<App/>',
components: { App }
})
Your main file should then look like this:
import Vue from 'vue'
import App from './App'
import VueI18n from 'vue-i18n'Vue.use(VueI18n)
Vue.config.productionTip = falseconst messages = {
en: {
message: {
hello: 'hello world'
}
},
fr: {
message: {
hello: 'Bonjour monde'
}
}
}// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'fr', // set locale
messages // set locale messages
})/* eslint-disable no-new */
new Vue({
i18n,
el: '#app',
template: '<App/>',
components: { App }
})
In your template, add the following markup:
<p>{{ $t("message.hello") }}</p>
Then launch your app, with:
$ npm run dev
Your code should output:
<p>Bonjour monde</p>
as we have set locale to ‘fr’.
If you change in your code to ‘en’, your app reload and your code should output:
<p>Hello world</p>
Wrapping up 🎉
That’s it for part 1 of this tutorial! In part 2 we’ll see some advanced features of vue-i18n that will be useful for your app!
The project is available on github:
VueJoy ebook is ready for preorder!
Learn VueJs with tutorial and examples.
Get new chapters as they’re completed and get updates!
Preorder now: http://www.vuejoy.com