Maxiss
Maxiss

Reputation: 1056

vue-i18n how to keep language after refresh/ access $i18n.locale in js (runtime)?

I don't know how to access $i18n.locale in runtime. Therefore I don't know how to keep it in my session, so that it doesn't go back to english when the page get refreshed.

<select class="dropdown-menu-lang " aria-labelledby="dropdown07" v-model="$i18n.locale" @change="langChanged($i18n.locale)" >
          <option class="dropdown-item-lang" v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
</select>

langs: ['fr', 'en'],

Here is what I tried

mounted(){
     if(localStorage.Lang!=null) $i18n.locale=localStorage.Lang; //how to access $i18n.locale ??
 },

langChanged(lang){
      localStorage.Lang=lang; //this is OK
},

And here is how I define everything in app.js

import Vue from 'vue';
import Vuetify from 'vuetify';
import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated.js';

Vue.use(VueInternationalization);

const lang = document.documentElement.lang.substr(0, 2); 

const i18n = new VueInternationalization({
    locale: lang,
    messages: Locale
});

Thank you very much

Upvotes: 5

Views: 3886

Answers (1)

Phillux
Phillux

Reputation: 43

Accessing $i18n in one of your child component's methods you must use "this"

mounted(){
 if(localStorage.Lang!=null) this.$i18n.locale=localStorage.Lang; 

},

Upvotes: 3

Related Questions