dendog
dendog

Reputation: 3328

Dynamically populate Vuex state

I need to load a different version of state based on a data variable in the root component.

App.vue:

export default {
  store : store,
  name: 'app',
  data() {
    clientId : 1  
  }
}

store.js:

export const store = new Vuex.Store({
  state : {
    clientConfig : clientConfig
});

And the clientConfig would be store in a separate file.

What is the best way to achieve a dynamic/programmatic loading of the Vuex state based on some input to the initial Vuejs App?

Thanks!

Upvotes: 0

Views: 3526

Answers (1)

ittus
ittus

Reputation: 22393

Here is 1 possible solution:

export const store = new Vuex.Store({
  state : {
    clientConfigs :{
      "1": clientConfig1,
      "2": clientConfig2
    },
    clientId: "1"
  },
  getters: {
    currentClientConfig: state => {
      return state.clientConfigs[state.clientId]
    }
  },
  mutations: {
   setClientId (state, newValue) {
     state.clientId = newValue
   }
  }
});

and in your component, you can access config by this.$store.getters.currentClientConfig

To update clientId, you can use mutations. In component, you can use this.$store.commit('setClientId', yourNewClientId)

Upvotes: 1

Related Questions