Search code examples
nuxt.jsvuexvuex-modules

Vuex whole state assign


I'm working with Nuxt and Vuex, and I'm trying to assign the whole namespaced-state to a certain value, It possible to assign the whole state? There is another way to have namespaced modules but assign a single value to the namespaced-state?

Some examples of the mutations I'm talking about

const mutations = {
  [SET_LOCATION](state, location) {
    state = { ...location }
  }
}

or

const mutations = {
  [SET_CURRENCY](state, currency) {
    switch(currency) {
      case 'MXN':
      case 'EUR':
        state = currency
        break
      default: 
        state = 'USD'
    }
  }
}

But, when these mutations are being executed, they do not assign the value, I have been trying to assign the value, but it only works when I assign a new value to a property of the namespaced-state.


Solution

  • but it only works when I assign a new value to a property of the namespaced-state

    This is happening for a reason. Vue has reactivity caveats. From the Docs

    Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

    To avoid this issue, make sure you declare all of your keys in the "state" object when you initialize the store

    For example:

    
    state = {locationState:null}
    // Make the store with the state
    const mutations = {
      [SET_LOCATION](state, location) {
        state.locationState = location 
      }
    }
    

    Let me know if that works for you.