1
votes

I have a getter inside a Vuex module. I change the value with a mutator and the state property changes, but the getter property is still the same, it doesn't react.

Then when I try to move the getter to the main Vuex store, it is reactive and works. I don't know why the module isn't reactive?

Here is Vuex store:

import {mymodule} from './vuex-modules' 
  
export default new Vuex.Store({ 
    modules: {  mymodule }, 
    getters: {},
    mutations: {
        updateState(state, payload) { 
            this.state[payload.stateName] = payload.newValue;
        },
    }, 
})

And the module:

export const mymodule = { 
    state: {  
        myproperty: ['defaultvalue']              //<-- the property is in the module's state
    },
    getters: {  
        myproperty: state => state.myproperty      //<-- getting myproperty from local state
    }, 
}

In the component I have a computed property with mapGetters:

computed: {
      ...mapGetters({ 
         myproperty: 'myproperty'
    }),

I make a commit from the component (calls updateState in mutations):

 let object = { stateName: 'myproperty', newValue:'newelement' }  
 this.$store.commit('updateState', object);

The Vuex state changes, but the computed property is unchanged.

I can simply move the getter from the module into the Vuex store:

export default new Vuex.Store({

    modules: { mymodule }, 
    getters: {
        myproperty: state => state.myproperty
    },

Now it works, the computed property myproperty has 'newelement' instead. What can be the problem?

UPDATE

So I can't use this.state[payload.stateName] inside the mutation, I have to specify which module it lies in. But how can I make it dynamic then? I thought it was like mixins where it was merged together.

Is there a way to target a state property in a mutator without having to specify the module it may be in?

Otherwise I can't have a mutator that is common for both the main state and modules.

1

1 Answers

1
votes

I have now understood that the mutator didn't access the module's property, it was only accessing its own state properties. So it was adding a new property to the main state while the target property was inside the module.

So this:

mutations: {
 updateState(state, payload) {
            
      state[payload.stateName] = payload.newValue;
 },

Should be:

state.mymodule[payload.stateName] = payload.newValue;

So this is why it happened I guess. But I have something to add in an edit to the question.