Vue i18n Implementing translations in Vue.js
vue-i18n
Instead of using a dot based key to fetch a translated string, it just uses the default string itself as the key.
In short {{ $t('Hello world') }}
instead of {{ $t('messages.hello_world') }}
.
Installation
npm install voo-i18n
import Vue from 'vue'
import i18n from 'voo-i18n'
const translations = {
'es': {
'Hello world': 'Hola Mundo'
},
'fr': {
'Hello world': 'Bonjour le monde'
},
'pirate': {
'Hello world': 'Land ho!'
}
}
Vue.use(i18n, translations)
Usage
Set a default locale in the root data of your application.
<template>
<h1>{{ 'Hello world' | translate }}</h1>
</template>
<script>
export default {
data () {
return {
locale: 'en'
}
}
}
</script>
And then the translations will be reactive to changes in the locale
value.
Specific locale
You can select a specific locale by passing in the locale param
<h1>{{ $t('Hello world', { locale: 'es' }) }}</h1>
Fallback locales
Localization carries the problem of different languages having different dialects. For example, french vs. canadian french. You can make distinctions as such:
export default {
'fr': {
'Hello world': 'Bonjour le monde',
'Goodbye': 'Au Revoir'
},
'fr_CA': {
'Hello world': 'Bonjour tout le monde, du Canada'
}
}
When the locale is set to fr_CA
, {{ 'Goodbye' | translate }}
still translates to 'Au Revoir'
.
For more visit the Github page