Skip to content

Commit a277be8

Browse files
save in localstorage and emit change from children to father
1 parent ce94cf1 commit a277be8

File tree

5 files changed

+115
-27
lines changed

5 files changed

+115
-27
lines changed

README-PT.md

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,6 @@ Use o seguinte comando para instalar o plugin como dependência:
1414

1515
npm install vue-multilanguage --save
1616

17-
#### Para instalação standalone
18-
19-
Para instalar, copie o arquivo `src/es6.js` para sua pasta de plugins.
20-
2117

2218
### Começando
2319

@@ -61,7 +57,7 @@ Podemos ainda definir parâmetros sem nome, usando `{0}`, assim na diretiva pass
6157
</template>
6258
<script>
6359
export default {
64-
data() { return {} }
60+
data() { return {} },
6561
messages: {
6662
en: {
6763
hi: 'Hello'
@@ -84,7 +80,7 @@ Você também pode incorporar o idioma padrão diretamente no seu template, desd
8480
</template>
8581
<script>
8682
export default {
87-
data() { return {} }
83+
data() { return {} },
8884
messages: {
8985
pt: {
9086
hi: 'Olá'
@@ -114,7 +110,7 @@ Note que você ainda pode usar substituições ao configurar mensagens padrão c
114110
```
115111

116112
### Uso na programação
117-
Existe um método `translate 'que você pode usar para recuperar uma tradução. Por exemplo:
113+
Existe um método `translate` que você pode usar para recuperar uma tradução. Por exemplo:
118114

119115
```js
120116
computed: {
@@ -124,11 +120,45 @@ computed: {
124120
}
125121
```
126122

123+
### Alterando a linguagem atual
124+
127125
Para alterar a linguagem atualmente usada pelo sistema altere o valor da opção `$language` em qualquer um de seus componentes por exemplo:
128126

129127
this.$language = 'en'
130128

131-
A linguagem padrão será pego automaticamente no navegador do cliente, caso não encontre-mos, o primeiro idioma da lista será usado.
129+
A partir da versão 2.2.3, todo componente que mudar a linguagem estará disparando um `$emit` nomeado `changeLang`, facilitando assim que filhos que alteram o idioma do site propaguem a alteração para seu pai, por exemplo:
130+
131+
```vue
132+
<template>
133+
<div id="app">
134+
<h1 v-lang.title.project v-show="false"></h1>
135+
...
136+
<lv-side-menu @changeLang="changeLanguage"></lv-side-menu>
137+
...
138+
</div>
139+
</template>
140+
141+
<script>
142+
import LvSideMenu from './components/template/SideMenu.vue'
143+
export default {
144+
name: 'app',
145+
components: { LvSideMenu },
146+
methods: {
147+
changeLanguage(lang) {
148+
this.$language = lang
149+
}
150+
},
151+
}
152+
</script>
153+
```
154+
155+
No exemplo dado, o componente `App` é pai de `LvSideMenu`, esse filho tratará de mudar o idioma do site, então ele emitirá o evento `changeLang`, que deve ser captado pelo pai para que a linguagem definida pelo filho seja propagada.
156+
157+
**Nota:** Veja que em `App` tenho o elemento oculto `h1`, ele faz uso da diretiva `v-lang`, pois sem ela o componente não seria atualizado.
158+
159+
### LocalStorage
160+
161+
A partir da versão 2.2.3 do vue-multilanguage, estamos gravando a linguagem atual na variável `vue-lang` do localStorage, fazendo com que mesmo ao atualizar a página a linguagem permaneça ativa.
132162

133163
### Contribuindo
134164

README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,12 +126,54 @@ computed: {
126126
}
127127
}
128128
```
129+
130+
### Change the current language
131+
129132
To change the language currently used by the system, change the `$ language` option value to any of its components, for example:
133+
130134
```js
131135
this.$language = 'en'
132136
```
137+
133138
If you don't set a default language on the language object, the default language will be automatically picked up in the client browser. If no language can still be found or you're in a JavaScript environment outside the browser (such as Node.js), then the default language becomes the first language listed.
134139

140+
this.$language = 'en'
141+
142+
As of version 2.2.3, the whole thing is to change the language by firing a `$emit` named `changeLang`, thus making it easier for children who change the language of the site to propagate a change to their parent, for example:
143+
144+
```vue
145+
<template>
146+
<div id="app">
147+
<h1 v-lang.title.project v-show="false"></h1>
148+
...
149+
<lv-side-menu @changeLang="changeLanguage"></lv-side-menu>
150+
...
151+
</div>
152+
</template>
153+
154+
<script>
155+
import LvSideMenu from './components/template/SideMenu.vue'
156+
export default {
157+
name: 'app',
158+
components: { LvSideMenu },
159+
methods: {
160+
changeLanguage(lang) {
161+
this.$language = lang
162+
}
163+
},
164+
}
165+
</script>
166+
```
167+
168+
In the example given, the `App` component is the parent of `LvSideMenu`, this child will try to change the language of the site, then it will issue the `changeLang` event, which must be captured by the parent so that the language defined by the child is propagated .
169+
170+
171+
**Note:** See that in `App` I have the `h1` hidden element, it makes use of the `v-lang` directive, because without it the component would not be updated.
172+
173+
### LocalStorage
174+
175+
As of version 2.2.3 of vue-multilanguage, we are writing the current language in the `vue-lang` variable of the localStorage, causing even the page refresh language to remain active.
176+
135177
### Contributing
136178

137179
To help in the development and expansion of this repository take a FORK to your account, after you have made your modifications do a PULL REQUEST, it will be parsed and included here since it helps the plugin.

demo/src/App.vue

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<div id="app">
33
<lv-menu-top></lv-menu-top>
44
<lv-content></lv-content>
5-
<lv-menu-bottom></lv-menu-bottom>
5+
<lv-menu-bottom @changeLang="changeLanguage"></lv-menu-bottom>
66
</div>
77
</template>
88

@@ -13,6 +13,11 @@ import LvContent from './Content.vue'
1313
1414
export default {
1515
name: 'app',
16-
components: {LvMenuTop, LvMenuBottom, LvContent}
16+
components: {LvMenuTop, LvMenuBottom, LvContent},
17+
methods: {
18+
changeLanguage(lang) {
19+
this.$language = lang
20+
}
21+
},
1722
}
1823
</script>

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vue-multilanguage",
3-
"version": "2.2.2",
3+
"version": "2.2.3",
44
"description": "Multilanguage easy support to VueJS 2",
55
"main": "dist/vue-multilanguage.js",
66
"module": "src/vue-multilanguage.js",
@@ -19,8 +19,8 @@
1919
"front-end"
2020
],
2121
"author": "Leonardo Vilarinho",
22-
"contributors": [{
23-
"name": "Matthew Dean",
22+
"contributors": [{
23+
"name": "Matthew Dean",
2424
"url": "https://github.com/matthew-dean"
2525
}],
2626
"license": "ISC",

src/vue-multilanguage.js

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
"use strict";
1+
'use strict';
22

3-
Object.defineProperty(exports, "__esModule", {
3+
Object.defineProperty(exports, '__esModule', {
44
value: true
55
});
66

7-
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
7+
var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; };
88

9-
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9+
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1010

11-
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
1212

1313
var MultiLanguage = function () {
1414
function MultiLanguage() {
@@ -50,6 +50,10 @@ var MultiLanguage = function () {
5050
userLang = Object.keys(this.languages)[0];
5151
}
5252
this.userLang = userLang;
53+
if (localStorage.getItem('vue-lang') !== null) {
54+
this.userLang = localStorage.getItem('vue-lang')
55+
}
56+
window.localStorage.setItem('vue-lang', this.userLang)
5357
}
5458

5559
/* get modifiers from directive, find in languages object and replace values */
@@ -165,15 +169,6 @@ var MultiLanguage = function () {
165169
match = path;
166170
}
167171
}
168-
/* if language = 'en', match a 'en-CA' language key */
169-
// if( !match ) {
170-
// Object.keys(this.languages).forEach((path) => {
171-
// path = path.toLowerCase()
172-
// if(lang.toLowerCase() === path.substr(0,2)) {
173-
// match = path
174-
// }
175-
// })
176-
// }
177172
);return match;
178173
}
179174
}]);
@@ -197,6 +192,22 @@ MultiLanguage.install = function (Vue, languages) {
197192
init.call(this, options);
198193
};
199194

195+
Vue.mixin({
196+
data() {
197+
return { isToggleLanguage: false }
198+
},
199+
created: function () {
200+
this.$language = window.localStorage.getItem('vue-lang')
201+
this.$forceUpdate()
202+
},
203+
watch: {
204+
$language(val) {
205+
window.localStorage.setItem('vue-lang', val)
206+
this.$emit('changeLang', val)
207+
}
208+
},
209+
})
210+
200211
Vue.prototype.translate = function (language, path) {
201212
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
202213

0 commit comments

Comments
 (0)