How to call multiple namespaced modules in vuex?

Member

by adan , in category: Javascript , a year ago

How to call multiple namespaced modules in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a year ago

@adan 

To call multiple namespaced modules in Vuex, you can use the dispatch and commit functions provided by Vuex.


First, make sure that you have defined your namespaced modules in the Vuex store by setting the namespaced option to true. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
import module1 from './module1';
import module2 from './module2';

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    module1,
    module2
  }
});

export default store;


Next, you can call actions, mutations, or getters from these namespaced modules using the dispatch and commit functions in your components. For actions or mutations, specify the namespace by passing the { root: true } option as the second argument to dispatch or commit. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// MyComponent.vue
export default {
  methods: {
    // Call an action in module1
    callActionInModule1() {
      this.$store.dispatch('module1/someAction');
    },
    // Call a mutation in module2
    callMutationInModule2() {
      this.$store.commit('module2/someMutation');
    },
    // Call a getter in module1
    callGetterInModule1() {
      const value = this.$store.getters['module1/someGetter'];
      console.log(value);
    }
  }
}


Note: When calling getters from namespaced modules in Vuex 2.x, you need to use the getters['module1/someGetter'] syntax. However, Vuex 4.x introduced a simplified syntax for accessing namespaced modules, allowing you to directly access the getters using this.$store.getters.someGetter as well.