1
votes

Setting language with a select list (using kazupon/vue-i18n plugin):

<select v-model="$i18n.locale" class="nav__lang-switcher">
  <option v-for="(lang, i) in langs" :key="`lang${i}`" :value="lang.value">{{ lang.label }}</option>
</select>

But language changes are not persisting because it's not being stored anywhere.

Here's the action, that would change the language state:

  actions: {
    changeLanguage (context) {
      context.commit('changeLanguage')
    }
  }

But how do i access $i18n.language from vuex store?

1

1 Answers

4
votes

You can pass this.$i18n as a parameter to action

actions: {
   changeLanguage (context, payload) {
     context.commit('changeLanguage')
     payload.i18n.locale = payload.lang
   }
}

In your component, there is a place where you change:

 onLanguageChange () {
   this.changeLanguage({ lang: this.selectedLang, i18n: this.$i18n })
 }

More thought

You should store lang in localStorage, too. In case user hard-refresh page, we can still load lang from local storage:

Something like:

const LANG_KEY = 'language'

const initLang = (() => {
  let lang = window.localStorage.getItem(LANG_KEY) || window.navigator.language
  return lang || 'en'
})()

const state = {
  lang: initLang
}

const actions = {
  changeLanguage ({ commit }, payload) {
    commit('onLangChanged', payload)
  }
}

const mutations = {
  onLangChanged (state, payload) {
    window.localStorage.setItem(LANG_KEY, payload.lang)
    payload.i18n.locale = payload.lang
    state.lang = payload.lang
  }
}