vuex-i18n
This is a fork from vuex-i18n with enhancements for vue3. The plugin can be used as Plugin or as Composition API.
Simple example applications for both, as plugin and as composition API can be found in the examples folder. Both examples use vite as build tool. Run apps via npm run dev
.
The APIs remain largley unchanged with the main different being the removal of translation filters. Filters are not supported in vue 3.
Requirements
- Vue ^3.0.0
- Vuex ^4.0.0-rc.1 (or newer)
Installation
$ npm install @unify/vuex-i18n
Setup
The vuex-i18n plugin is intended to be used for applications that use vuex as
store and require localized messages. Make sure that both vue and vuex have
been loaded beforehand.
The plugin provides a vuex module to store the localization information and
translations and a plugin to allow easy access from components.
The plugin does not make any assumption on how you want to load the localization
information. It can be loaded on start in your application bundle or dynamically
after when the user is switching to a different language.
Use as Plugin
import { createApp } from 'vue'
import { createStore } from 'vuex'
import { createI18nPlugin, useI18nPlugin } from '@unify/vuex-i18n'
import App from './App.vue'
const app = createApp(App)
const store = createStore({})
app.use(store)
app.use(createI18nPlugin(store))
const i18n = useI18nPlugin()
i18n.add('en', { title: 'My Title'})
i18n.set('en')
app.mount('#app')
<template>
<div>{{ $t('title') }}</div>
</template>
<script>
export default { name: 'App' }
</script>
Use as Composition API
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from './App.vue'
const app = createApp(App)
app.use(createStore({}))
app.mount('#app')
<template>
<div>locale is: {{ locale() }}</div>
<div>{{ t('title') }}</div>
</template>
<script>
import { provideI18n, useI18n } from '@unify/vuex-i18n'
export default {
name: 'App',
setup() {
const i18n = provideI18n()
i18n.add('en', { title: 'My Title'})
i18n.set('en')
const { translate: t, locale } = i18n
return { t, locale }
}
}
</script>
Detailed usage
You can specify a custom module name for vuex (default is 'i18n') or a callback that is triggered
when a key has no translation for the current locale. Please note, that the function
supplied for onTranslationNotFound will be called if the key is not in the actual
locale or a parent locale (ie. en for en-us), however, the key might still be available
in the fallback locale.
If a return value is given, this will be used as translation text for the key
that was not found. It is also possible to return a promise. This will allow you
to dynamically fetch the data from an api. Be aware, that the key will only
be resolved once and then written like any other key into the store. Therefore
subsequent calls of the same key will not trigger the onTranslationNotFound method.
app.use(createI18nPlugin(store, {
moduleName: 'i18n',
onTranslationNotFound (locale, key) {
console.warn(`i18n :: Key '${key}' not found for locale '${locale}'`);
}}
));
app.use(createI18nPlugin(store, {
moduleName: 'i18n',
onTranslationNotFound (locale, key) {
switch(key) {
case: '200':
return 'Everything went fine';
break;
default:
return 'There was a problem';
}
}}
));
Vue.use(createI18nPlugin(store, {
moduleName: 'i18n',
onTranslationNotFound (locale, key) {
return new Promise((resolve, reject) => {
axios.get('/api/translations/async', {locale: locale, key:key})
.then((result) => {
resolve(result.data);
}).catch() {
reject();
}
})
}}
));
Config
You can pass a config object as the third parameter when use vuex-i18n.
i.e. Vue.use(vuexI18n.plugin, store, config)
At present, the configuration options that are supported are as follows:
moduleName
(default i18n
)
identifiers
(default ['{', '}']
)
preserveState
(default false
)
onTranslationNotFound
(default function(){}
)
warnings
: default(true
)
const config = {
moduleName: 'myName'
}
app.use(createI18nPlugin(store, config))
Usage
vuex-i18n provides easy access to localized information through the use of
the $t()
.
The plugin will try to find the given string as key in the translations of the
currently defined locale and return the respective translation. If the string
is not found, it will return as is. This wil allow you to setup an application
very quickly without having to first define all strings in a separate template.
It is also possible to specify a fallback-locale $i18n.fallback(locale)
. If
the key is not found in current locale, vuex-i18n will look for the key in the
fallback-locale. If the key can not be found in the fallback-locale either,
the key itself will be returned as translation.
<div>
{{ $t('Some localized information')}}
</div>
In larger projects, it is often easier to use a more robust translation key instead
of the default text. Therefore it is also possible to specify the key and
default translation. The default value will only be used, if the key cannot be
found in the current and in the fallback locale.
<div>
{{ $t('non.existing.key', 'Default information text')}}
</div>
Dynamic parameters that can be passed to the translation method in the form of
key/value pairs.
<div>
{{ $t('You have {count} new messages', {count: 5}) }}
</div>
It is possible to specify custom identifiers for variable substitutions. The
respective identifiers - start and stop - must be passed when initializing the
module. Please note that a regular expression is used to match the tags.
Therefore it might be necessary to escape certain characters accordingly.
app.use(createI18nPlugin(store, {
identifiers: ['{{','}}']
}));
Basic pluralization is also supported. Please note, that the singular translation
must be specified first, followed by plural translations denoted by :::
.
Up to six pluralization forms are supported based on configuration taken from vue-gettext.
The second option is used for variable replacements. The third option to define if
the singular or pluralized translation should be used (see below for examples).
<div>
{{ $t('You have {count} new message ::: You have {count} new messages', {count: 5}, 5) }}
{{ $t('mykey', {count: 5}, 5) }}
const translations = {
'mykey': 'You have {count} new message ::: You have {count} new messages'
}
const translations = {
'mykey': [
'You have {count} new message',
'You have {count} new messages'
]
}
</div>
<div>
{{ $t('{count} bērns ::: {count} bērni ::: {count} bērnu', {count: 5}, 5) }}
</div>
The current locale can be set using the $i18n.set()
method. By default, the
translation method will select the pre-specified current locale. However, it is
possible to request a specific locale using the $tlang()
method.
<div>
{{ $tlang('en', 'You have {count} new messages', {count: 5}) }}
</div>
There are also several methods available on the property this.$i18n
or Vue.i18n
$t(), i18n.translate()
i18n.translateIn()
i18n.locale()
i18n.locales()
i18n.set(locale)
i18n.add(locale, translations)
i18n.replace(locale, translations)
i18n.remove(locale)
i18n.fallback(locale)
i18n.localeExists(locale)
i18n.keyExists(key)
i18n.keyExists(key, 'strict'), i18n.keyExists(key, 'locale'), i18n.keyExists(key, 'fallback'),
Contributions
Any comments or suggestions are very welcome.