Setting Up State Management (Vuex) for Vue Application
Vuex is the legacy state management for Vue 2. Structured with stores, mutations, actions, and getters. Still widely used in Vue 2 projects and legacy Vue 3 applications.
For new Vue 3 projects, use Pinia instead.
What's Involved
Setting up Vuex store structure, organizing mutations, actions, and getters, module splitting, devtools integration, testing.
Installation
npm install vuex@next # for Vue 3
Basic Store
import { createStore } from 'vuex'
export default createStore({
state: () => ({
items: [] as CartItem[],
}),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
count: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),
},
mutations: {
ADD_ITEM(state, item: CartItem) {
const existing = state.items.find(i => i.id === item.id)
if (existing) existing.qty++
else state.items.push({ ...item, qty: 1 })
},
},
actions: {
addItem({ commit }, item: CartItem) {
commit('ADD_ITEM', item)
},
},
})
Usage:
<script>
export default {
computed: {
cartCount() { return this.$store.getters.count }
},
methods: {
add(item) { this.$store.dispatch('addItem', item) }
}
}
</script>
Timeline
Basic Vuex setup — 1–2 hours. Full store with modules — 1 day. Migration from Vuex to Pinia — 2–3 days for large projects.







