Sonia
Sonia

Reputation: 195

Use vuex state in Vuetify.js plugin

I'm getting very confused about calling a vuex state inside the Vuetify.js plugin.

My project is to translate a website based on the users preferred language. I've completely setup the translations with i18n. This project consists of 2 parts.

  1. The translation based on JSON files (This is working just fine)
  2. The translation of the Vuetify components based on the translations provided by Vuetify.

The 2nd point is where I get stuck. According to the manual from Vuetify you need to import the needed language files inside the Vuetify.js plugin. This all works perfect.

But...I can only change it manually....

What I want to achieve is that the correct Vuetify language gets set based in the language set inside my vuex store. Believe me, I've been search the internet for days and tried everything that I could find. But nothing seems to work. I can't seem to figure out how to call the vuex state inside the Vuetify.js plugin.

import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

import nl from 'vuetify/es5/locale/nl'
import fr from 'vuetify/es5/locale/fr'
import en from 'vuetify/es5/locale/en'

Vue.component('my-component', {
 methods: {
    changeLocale() {
        this.$vuetify.lang.current
    },
 },
})
export default new Vuetify({
 lang: {
    locales: { nl, en, fr },
    current: "nl",
},
})

So the state of current should be based on the state in my vuex store.

Here is my vuex store

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import i18n, { selectedLocale } from './i18n'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    locale: selectedLocale
  },
  mutations: {
    updateLocale(state, newLocale) {
      state.locale = newLocale
    }
  },
  actions: {
    changeLocale({ commit }, newLocale) {
      i18n.locale = newLocale
      commit('updateLocale', newLocale)
    }
  },
  plugins: [createPersistedState()]
})

Who can point me in the right direct on who to go about this?

Upvotes: 3

Views: 1170

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14279

When you change the locale in i18n you should also change it in Vuetify:

export default new Vuex.Store({
  state: {
    locale: selectedLocale
  },
  mutations: {
    updateLocale(state, newLocale) {
      state.locale = newLocale
    }
  },
  actions: {
    changeLocale({ commit }, { newLocale, currentVueComponent }) {
      i18n.locale = newLocale
      currentVueComponent.$vuetify.lang.current = newLocale // <--- the important code
      commit('updateLocale', newLocale)
    }
  },
  plugins: [createPersistedState()]
})

Upvotes: 1

Related Questions