Modules and Advanced Usage
🎯 Introduction
Vuex is an important state management tool in frontend development, particularly in Vue 2.0 projects. As a project grows more complex, a single store can become bloated and difficult to maintain. Modules, helper functions, and state persistence help address these challenges.
🧐 Why Use Modules?
As a project grows, a single store can become large and disorganized. Maintenance becomes difficult, especially when several developers edit the same large file and run into conflicts.
Modules give each business area its own smaller store-like unit with clear responsibilities. Team members can work within well-defined boundaries, reducing the need for coordination.
An Example
For an e-commerce website, you might define:
- A user module: manages login state, user information, and related data
- A product module: manages product listings and details
- A cart module: manages shopping cart data
- An order module: manages order-related state
Each module acts as a small store that manages its own data and behavior.
📦 What Is a Module?
Vuex lets you split a store into modules, each with its own state, mutations, actions, and getters. This separates different areas of business logic and makes the code clearer and easier to maintain.
Consider an everyday analogy:
Imagine a large bookshelf filled with books. If all the books are piled into one compartment, finding a particular book is difficult. Modules are like separate compartments for novels, reference books, magazines, and other categories. You can immediately see where each type belongs and find what you need.
Example Module Structure
const moduleA = {
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
},
},
getters: {
doubleCount(state) {
return state.count * 2;
},
},
};
Then register the module in the root store:
const store = new Vuex.Store({
modules: {
a: moduleA,
},
});
The state and handlers in moduleA are now organized as a separate module.
✍️ Simplifying Component Code
Accessing Vuex state and calling store methods directly in components, with expressions such as this.$store.state.a.count or this.$store.commit('a/increment'), can become verbose.
Vuex provides several helper functions to simplify this code:
mapState: maps module state to component computed propertiesmapGetters: maps module getters to computed propertiesmapActions: maps module actions to component methods
Example
Using module a from above, the component code with these helpers looks like this:
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double count: {{ doubleCount }}</p>
<button @click="incrementAsync">Increment asynchronously</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
computed: {
...mapState('a', ['count']),
...mapGetters('a', ['doubleCount']),
},
methods: {
...mapActions('a', ['incrementAsync']),
},
};
</script>
Here, 'a' identifies the module namespace, telling Vuex where to find the corresponding state and handlers.
mapState, mapGetters, and mapActions makes code shorter and clearer, especially in large projects.💾 Persisting State
By default, Vuex state exists only in memory and is lost when the page reloads. To improve the user experience, applications often persist selected state in the browser's localStorage.
Basic Approach
Whenever Vuex state changes, serialize it and save it to localStorage. When the page initializes, read the saved state from localStorage and restore it in Vuex.
Example Code
state: {
token: null,
username: localStorage.getItem('name') || null,
email: '',
},
mutations: {
setToken(state, token) {
state.token = token;
localStorage.setItem('token', token); // ✅ Save directly
},
}
localStorage, as this can introduce security risks or performance issues.❓ Knowledge Check
Q1: What are the benefits of modules?
Modules give state management clear responsibilities, separate business areas, and keep the code structure easy to maintain and work on as a team.
Q2: How does mapState differ from accessing this.$store.state directly?
mapState automatically maps module state to computed properties, reducing code and making reactive component updates straightforward.
Q3: Why should you avoid persisting all state?
Some state contains sensitive information or dynamic data. Saving it in localStorage can create security and performance risks.
🧪 Practice
Using the template below, implement a Vuex shopping cart module with a list of items and the ability to add items. Access it from a component with mapState and mapActions.
const cart = {
state: {
items: [],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItem({ commit }, item) {
commit('addItem', item);
},
},
getters: {
itemCount(state) {
return state.items.length;
},
},
};
export default cart;
import Vuex from 'vuex';
import Vue from 'vue';
import cart from './modules/cart';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
cart,
},
});
export default store;
<template>
<div>
<p>Items in cart: {{ itemCount }}</p>
<button @click="addItem({ id: 1, name: 'Product A' })">Add Product A</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
computed: {
// Fill this in
},
methods: {
// Fill this in
},
};
</script>
🎉 You now know how to organize Vuex into modules, simplify component code, and persist state! These techniques help you organize state in large Vue 2.0 projects, keep code clear, and improve the user experience.
Understanding Vuex Core Features
Explore getters, actions, and mutations in Vuex, and learn why synchronous state changes and asynchronous operations have separate responsibilities.
Getting Started with Element UI
Learn why UI frameworks are useful, what Element UI provides, and how to install it in Vue 2 projects using full or on-demand imports.
