UNPKG

11.9 kBMarkdownView Raw
1# vuex-i18n
2We are big fans of the awesome vue, vuex and vue-router libraries and were just
3looking for an easy to use internationalization plugin, employing as much of
4the "standard library" as possible.
5
6The main difference to other internationalization plugins is the ease of use
7and support for locales directly with the application or later from the server.
8
9## Requirements
10- Vue ^2.0.0
11- Vuex ^2.0.0
12
13## Installation
14```
15$ npm install vuex-i18n
16```
17
18## Setup
19The vuex-i18n plugin is intended to be used for applications that use vuex as
20store and require localized messages. Make sure that both vue and vuex have
21been loaded beforehand.
22
23The plugin provides a vuex module to store the localization information and
24translations and a plugin to allow easy access from components.
25
26The plugin does not make any assumption on how you want to load the localization
27information. It can be loaded on start in your application bundle or dynamically
28after when the user is switching to a different language.
29
30A corresponding example can be found in the test directory.
31
32```javascript
33
34// load vue and vuex instance
35import Vue from 'vue';
36import Vuex from 'vuex';
37
38// load vuex i18n module
39import vuexI18n from 'vuex-i18n';
40
41// IMPORTANT NOTE:
42// The default format for the plugin is in es2015, if you do not use a transpiler
43// such as babel) or for use in server side rendering (such as nuxt)
44// the umd version should be loaded like this
45// import vuexI18n from 'vuex-i18n/dist/vuex-i18n.umd.js';
46
47// initialize the vuex store using the vuex module. note that you can change the
48// name of the module if you wish
49const store = new Vuex.Store();
50
51// initialize the internationalization plugin on the vue instance. note that
52// the store must be passed to the plugin. the plugin will then generate some
53// helper functions for components (i.e. this.$i18n.set, this.$t) and on the vue
54// instance (i.e. Vue.i18n.set).
55Vue.use(vuexI18n.plugin, store);
56
57// please note that you must specify the name of the vuex module if it is
58// different from i18n. i.e. Vue.use(vuexI18n.plugin, store, {moduleName: 'myName'})
59
60
61// add some translations (could also be loaded from a separate file)
62// note that it is possible to use placeholders. translations can also be
63// structured as object trees and will automatically be flattened by the the
64// plugin
65const translationsEn = {
66 "content": "This is some {type} content"
67};
68
69// translations can be kept in separate files for each language
70// i.e. resources/i18n/de.json.
71const translationsDe = {
72 "My nice title": "Ein schöner Titel",
73 "content": "Dies ist ein toller Inhalt"
74};
75
76// add translations directly to the application
77Vue.i18n.add('en', translationsEn);
78Vue.i18n.add('de', translationsDe);
79
80// set the start locale to use
81Vue.i18n.set('en');
82
83// create a new component (requires a div with id app as mount point)
84// you can use the method $t to access translations. the value will be returned
85// as is, if no corresponding key is found in the translations
86var app = new Vue({
87 store,
88 el: '#app',
89 template: `
90 <div>
91 <h1>{{ 'My nice title' | translate }}</h1>
92 <p>{{ $t('content', {'type': 'nice'}) }}</p>
93 </div>
94 `
95});
96
97```
98
99You can specify a custom module name for vuex (default is 'i18n') or a callback that is triggered
100when a key has no translation for the current locale. Please note, that the function
101supplied for onTranslationNotFound will be called if the key is not in the actual
102locale or a parent locale (ie. en for en-us), however, the key might still be available
103in the fallback locale.
104
105If a return value is given, this will be used as translation text for the key
106that was not found. It is also possible to return a promise. This will allow you
107to dynamically fetch the data from an api. Be aware, that the key will only
108be resolved once and then written like any other key into the store. Therefore
109subsequent calls of the same key will not trigger the onTranslationNotFound method.
110
111```javascript
112
113// without return value (will use fallback translation, default translation or key)
114Vue.use(vuexI18n.plugin, store, {
115 moduleName: 'i18n',
116 onTranslationNotFound (locale, key) {
117 console.warn(`i18n :: Key '${key}' not found for locale '${locale}'`);
118 }}
119);
120
121// with string as return value. this will write the new value as translation
122// into the store
123// note: synchronous resolving of keys is not recommended as this functionality
124// should be implemented in a different way
125Vue.use(vuexI18n.plugin, store, {
126 moduleName: 'i18n',
127 onTranslationNotFound (locale, key) {
128 switch(key) {
129 case: '200':
130 return 'Everything went fine';
131 break;
132 default:
133 return 'There was a problem';
134 }
135 }}
136);
137
138// with promise as return value. this will write the new value into the store,
139// after the promise is resolved
140Vue.use(vuexI18n.plugin, store, {
141 moduleName: 'i18n',
142 onTranslationNotFound (locale, key) {
143
144 return new Promise((resolve, reject) => {
145 axios.get('/api/translations/async', {locale: locale, key:key})
146 .then((result) => {
147 resolve(result.data);
148
149 }).catch() {
150 reject();
151 }
152
153 })
154
155 }}
156);
157
158```
159## Config
160You can pass a config object as the third parameter when use vuex-i18n.
161i.e. Vue.use(vuexI18n.plugin, store, config)
162
163At present, the configuration options that are supported are as follows:
164
165- `moduleName` (default `i18n`)
166- `identifiers` (default `['{', '}']`)
167- `preserveState` (default `false`)
168- `translateFilterName` (default `translate`)
169- `onTranslationNotFound` (default `function(){}`)
170- `warnings`: default(`true`)
171
172```javascript
173
174const config = {
175 moduleName: 'myName',
176 translateFilterName: 't'
177}
178
179Vue.use(vuexI18n.plugin, store, config)
180
181```
182
183## Usage
184vuex-i18n provides easy access to localized information through the use of
185the `$t()` method or the `translate` filter.
186
187The plugin will try to find the given string as key in the translations of the
188currently defined locale and return the respective translation. If the string
189is not found, it will return as is. This wil allow you to setup an application
190very quickly without having to first define all strings in a separate template.
191
192It is also possible to specify a fallback-locale `$i18n.fallback(locale)`. If
193the key is not found in current locale, vuex-i18n will look for the key in the
194fallback-locale. If the key can not be found in the fallback-locale either,
195the key itself will be returned as translation.
196
197```javascript
198<div>
199 // will return: "Some localized information"
200 {{ $t('Some localized information')}}
201</div>
202
203```
204
205In larger projects, it is often easier to use a more robust translation key instead
206of the default text. Therefore it is also possible to specify the key and
207default translation. The default value will only be used, if the key cannot be
208found in the current and in the fallback locale.
209
210```javascript
211<div>
212 // will return: "Default information text" if the key non.existing.key is
213 // not specified in the current and the fallback locale
214 {{ $t('non.existing.key', 'Default information text')}}
215</div>
216```
217
218Dynamic parameters that can be passed to the translation method in the form of
219key/value pairs.
220
221```javascript
222<div>
223 // will return: "You have 5 new messages"
224 {{ $t('You have {count} new messages', {count: 5}) }}
225</div>
226```
227
228It is possible to specify custom identifiers for variable substitutions. The
229respective identifiers - start and stop - must be passed when initializing the
230module. Please note that a regular expression is used to match the tags.
231Therefore it might be necessary to escape certain characters accordingly.
232
233```javascript
234// i.e. to use {{count}} as variable substitution.
235Vue.use(vuexI18n.plugin, store, {
236 identifiers: ['{{','}}']
237});
238```
239
240Basic pluralization is also supported. Please note, that the singular translation
241must be specified first, followed by plural translations denoted by `:::`.
242Up to six pluralization forms are supported based on configuration taken from [vue-gettext](https://github.com/Polyconseil/vue-gettext).
243The second option is used for variable replacements. The third option to define if
244the singular or pluralized translation should be used (see below for examples).
245
246
247```javascript
248<div>
249 // will return: "You have 5 new messages" if the third argument is 5"
250 // or "You have 1 new message" if the third argument is 1
251 // or "You have 0 new messages" if the third argument is 0 (note pluralized version)
252
253 // using the translation directly (as specified in the current readme)
254 {{ $t('You have {count} new message ::: You have {count} new messages', {count: 5}, 5) }}
255
256
257 // using a key to lookup the translations
258 {{ $t('mykey', {count: 5}, 5) }}
259
260 // in the store
261 const translations = {
262 'mykey': 'You have {count} new message ::: You have {count} new messages'
263 }
264
265 // alternative specification with array for translations
266 const translations = {
267 'mykey': [
268 'You have {count} new message',
269 'You have {count} new messages'
270 ]
271 }
272</div>
273```
274
275```javascript
276<div>
277 // In case when there are more than singular and plural versions like in Latvian language.
278 // will return: "5 bērni" (in english - 5 children) if the third argument is 5"
279 // or "2 bērni" if the third argument is 2
280 // or "1 bērns" if the third argument is 1
281 // or "0 bērnu" if the third argument is 0
282 {{ $t('{count} bērns ::: {count} bērni ::: {count} bērnu', {count: 5}, 5) }}
283</div>
284```
285
286The current locale can be set using the `$i18n.set()` method. By default, the
287translation method will select the pre-specified current locale. However, it is
288possible to request a specific locale using the `$tlang()` method.
289
290```javascript
291<div>
292 // will return the english translation regardless of the current locale
293 {{ $tlang('en', 'You have {count} new messages', {count: 5}) }}
294</div>
295```
296
297There are also several methods available on the property `this.$i18n` or `Vue.i18n`
298
299```javascript
300
301// translate the given key
302$t(), Vue.i18n.translate()
303
304// translate the given key in a specific locale
305$tlang(), Vue.i18n.translateIn()
306
307// get the current locale
308$i18n.locale(), Vue.i18n.locale()
309
310// get all available locales
311// is is however recommended to use a computed property to fetch the locales
312// returning Object.keys(this.$store.state.i18n.translations); as this will
313// make use of vue's caching system.
314$i18n.locales(), Vue.i18n.locales()
315
316// set the current locale (i.e. 'de', 'en')
317$i18n.set(locale), Vue.i18n.set(locale)
318
319// add locale translation to the storage. this will extend existing information
320// (i.e. 'de', {'message': 'Eine Nachricht'})
321$i18n.add(locale, translations), Vue.i18n.add(locale, translations)
322
323// replace locale translations in the storage. this will remove all previous
324// locale information for the specified locale
325$i18n.replace(locale, translations), Vue.i18n.replace(locale, translations)
326
327// remove the given locale from the store
328$i18n.remove(locale), Vue.i18n.remove(locale)
329
330// set a fallback locale if translation for current locale does not exist
331$i18n.fallback(locale), Vue.i18n.fallback(locale)
332
333// check if the given locale translations are present in the store
334$i18n.localeExists(locale), Vue.i18n.localeExists(locale)
335
336// check if the given key is available (will check current, regional and fallback locale)
337$i18n.keyExists(key), Vue.i18n.keyExists(key)
338
339// optional with a second parameter to limit the scope
340// strict: only current locale (exact match)
341// locale: current locale and parent language locale (i.e. en-us & en)
342// fallback: current locale, parent language locale and fallback locale
343// the default is fallback
344$i18n.keyExists(key, 'strict'), $i18n.keyExists(key, 'locale'), $i18n.keyExists(key, 'fallback'),
345
346```
347
348## Third-Party Integration
349Thanks to Liip Team Amboss for developing an interactive translation manager for node.js. You can find it at https://github.com/liip-amboss/locale-man.
350
351
352## Contributions
353Any comments or suggestions are very welcome.