How to use Vuex store
Vuex provides centralized state management for Vue applications, enabling predictable data flow and shared state across multiple components. With over 25 years of experience building complex applications and as the creator of CoreUI, I’ve used Vuex extensively for managing application-wide state. The most effective approach is creating a centralized store with clearly defined state, mutations, and actions for data management. This ensures consistent data handling and makes debugging and testing significantly easier.
Use Vuex createStore to set up centralized state management with state, mutations, and actions for your Vue application.
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state: {
user: null,
isAuthenticated: false,
notifications: []
},
mutations: {
SET_USER(state, user) {
state.user = user
state.isAuthenticated = !!user
},
ADD_NOTIFICATION(state, notification) {
state.notifications.push(notification)
}
},
actions: {
async loginUser({ commit }, credentials) {
const user = await api.login(credentials)
commit('SET_USER', user)
}
}
})
// main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).use(store).mount('#app')
This Vuex store defines state for user authentication and notifications. Mutations like SET_USER directly modify state, while actions like loginUser handle asynchronous operations before committing mutations. The store is registered with the Vue app using use(store), making it accessible to all components through $store or the composition API.
Best Practice Note:
This state management pattern is used throughout CoreUI Vue templates for consistent, scalable data handling. Always use mutations for state changes and actions for async operations to maintain predictable state updates and enable proper debugging with Vue DevTools.



