Blog>
Snippets

Modularizing Vuex Store in Vue 3

Demonstrate how to break down Vuex store into modules for better state management organization in a large-scale Vue 3 application.
// userModule.js
export default {
  namespaced: true,
  state() {
    return {
      users: []
    };
  },
  mutations: {
    addUser(state, user) {
      state.users.push(user);
    }
  },
  actions: {
    fetchUsers({ commit }) {
      // Simulate API call
      setTimeout(() => {
        const usersData = [{ name: 'John Doe' }, { name: 'Jane Doe' }];
        usersData.forEach(user => {
          commit('addUser', user);
        });
      }, 1000);
    }
  }
};
This is an example of a Vuex module for user management. It contains its own state, mutations, and actions that are scoped to user-related functionality. 'namespaced: true' makes it possible to have the same mutation/action names in different modules without collisions.
// productsModule.js
export default {
  namespaced: true,
  state() {
    return {
      products: []
    };
  },
  mutations: {
    addProduct(state, product) {
      state.products.push(product);
    }
  },
  actions: {
    fetchProducts({ commit }) {
      // Simulate API call
      setTimeout(() => {
        const productsData = [{ title: 'Widget' }, { title: 'Gadget' }];
        productsData.forEach(product => {
          commit('addProduct', product);
        });
      }, 1000);
    }
  }
};
This module manages the products state within the Vuex store. It, too, is namespaced to allow for isolated state management and to avoid naming conflicts in a larger application.
// store.js
import { createStore } from 'vuex';
import userModule from './userModule';
import productsModule from './productsModule';

const store = createStore({
  modules: {
    users: userModule,
    products: productsModule
  }
});

export default store;
Here we are creating the main Vuex store and registering the user and products modules. By defining 'modules', we are able to include all of our separate state management concerns neatly packaged into an organized and scalable store configuration.
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);
app.use(store);
app.mount('#app');
In this snippet, we are setting up and mounting the Vue application. It includes importing the configured store and telling Vue to use it with 'app.use(store)', which makes the store available to all components in the app.