0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.