A VueJS (1.x, 2.0+) plugin for basic translations.
Is a plugin to handle basic translations for your components, it adds a mixin and a directive to handle it the most comfortable way.
Yes and no, Vue-i18n is a great plugin and is a lot more complete than this. This handle translations too, but is a more basic idea and smaller file (is just one file!).
Just translations, it is that simple.
import Vue from 'vue';
import VueTranslate from 'vue-translate-plugin';
Vue.use(VueTranslate);
var myComp = Vue.extend({
template: `<div>
{{ t('Hello World') }}
<span v-translate>How are you?</span>
</div>`,
mounted() {
// Define what language you want to use.
// This can be called in something like a header with a language selector menu
// Or any other case, doesn't need to be called in all components, but
// at least in one, so it sets the global language of the plugin
this.$translate.setLang('es_DO');
},
// The translations itself, keyed by language or anything else you one
locales: {
es_DO: {
'Hello World': 'Hola Mundo',
'How are you?': 'Como estás?'
}
}
});
var vm = new Vue({
el: '#app',
components: {myComp},
template: `<div>
<my-comp></my-comp>
</div>`
});
You can do this in three different ways:
- A
locales
option in your component:
Vue.component({
...
locales: {
spanish: {
'hello world': 'hola mundo'
}
},
...
})
- Inside a component's method:
Vue.component({
methods: {
loadMysuperTranslation() {
this.$translate.setLocales({
spanish: {
'hello world': 'hola mundo'
}
});
}
}
});
- Globally when loading the plugin:
Vue.use(VueTranslate);
Vue.locales({
spanish: {
'hello world': 'hola mundo'
}
});
Use the setLang
method of the $translate
property, like this:
Vue.component({
methods: {
showAppInSpanish() {
this.$translate.setLang('spanish');
}
}
});
You can listen to custom events emitted by the $translate
property:
this.$translate.$on('language:changed', language => {
console.log('The user choose '+language);
})
You can use the method textWithParams
if you would like to insert parameters in your translation strings.
this.$translate.textWithParams('translation.string', {
keyA: 'Glenn',
keyB: 'John'
})
{{ tWithParams('translation.string', { keyA: 'Glenn', keyB: 'John' }) }}
// In locales.js
'translation.string': 'My name is %keyA%. My brother is named %keyB%.'
// Result
'My name is Glenn. My brother is named John.'
When the first language is set.
When the language to use was changed from the previous value.
Everytime a language is changed, either is the first time or not.
When locales are loaded either by any of the 3 options