Search code examples
javascriptvue.jsvuexvuex-modules

Using mapState and mapMutations from a namespaced module


I can't figure out how to access mutations and states after having split my vuex store into three modules. I've tried different syntaxes and I'm not sure what to follow.

MapStates: This is how I've set up the mapStates, vendor and root are the module names.

...mapState({
  vendor: state => state.vendor.vendor,
  language: state => state.root.language
})

and use it like this:

console.log(this.vendor);

MapMutations: I think I've set up the mapMutations correctly.

methods: {
  ...mapMutations('vendor', ['UPDATE_VENDOR', 'SET_VENDOR_APISTATE'])
}

and accessing it like this:

this.$store.commit('UPDATE_VENDOR', response.data);

or

this.UPDATE_VENDOR(response.data);

None of these seem to work for me and I can't figure out what I'm doing wrong.

My store looks like this:

import vendorModule from './vendor/vendorModule';

const store = new Vuex.Store({
  modules: {
    customer: customerModule,
    root: rootModule,
    vendor: vendorModule
  }
});

with modules like this:

const vendorModule = {
  namespaced: true,
  state: () => ({
    vendor: null,
    vendorApiState: ENUM.INIT
  }),
  mutations: {
    UPDATE_VENDOR(state, vendor) {
      state.vendor = vendor;
      state.vendorApiState = ENUM.LOADED;
    }
  }
};

export default {
  vendorModule
};

EDIT I realised that my modules where structured wrong. and as Kelvin Omereshone wrote I used the wrong syntax here: this.$store.commit('vendor/UPDATE_VENDOR', response.data);.

The working module structure is:

const state = () => ({
  vendor: null,
  vendorApiState: ENUM.INIT
});

const mutations = {
  UPDATE_VENDOR(state, vendor) {
    state.vendor = vendor;
    state.vendorApiState = ENUM.LOADED;
  }
};

export default {
  namespaced: true,
  state,
  mutations
};

Solution

  • If you want to use this.$store.commit('UPDATE_VENDOR', response.data);. No need for mapMutations. Just use it like so:

    this.$store.commit('vendor/UPDATE_VENDOR', response.data);
    

    Note: the module name comes before the Mutation name separated by a forward slash /