How to Use Vuex Store in Vue.js for State Management
To use the
Vuex store in Vue.js, first create a store with state, mutations, and actions, then register it in your Vue app. Access state with this.$store.state and update it by committing mutations with this.$store.commit.Syntax
The Vuex store is created by defining state (data), mutations (methods to change state), and optionally actions (async operations). You then register the store in your Vue app and access it via this.$store.
state: holds the data.mutations: synchronous functions to update state.actions: asynchronous functions that commit mutations.getters: compute derived state.
javascript
import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { doubleCount(state) { return state.count * 2 } } }) export default store
Example
This example shows how to create a Vue app using Vuex store to manage a counter. The button commits a mutation to increase the count, and the count is displayed from the store's state.
javascript
import { createApp } from 'vue' import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ } } }) const app = createApp({ computed: { count() { return this.$store.state.count } }, methods: { increment() { this.$store.commit('increment') } }, template: ` <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> ` }) app.use(store) app.mount('#app')
Output
Count: 0
[User clicks 'Increment' button]
Count: 1
[Clicks again]
Count: 2
Common Pitfalls
Common mistakes include trying to modify state directly instead of using mutations, forgetting to register the store with the Vue app, or accessing state outside of components without proper import.
Always use commit to change state, never assign state properties directly.
javascript
/* Wrong way: Direct state change */ this.$store.state.count++ // ❌ Do not do this /* Right way: Use mutation */ this.$store.commit('increment') // ✅ Correct approach
Quick Reference
| Concept | Usage |
|---|---|
| Create store | const store = createStore({ state, mutations, actions, getters }) |
| Register store | app.use(store) |
| Access state | this.$store.state.property |
| Commit mutation | this.$store.commit('mutationName') |
| Dispatch action | this.$store.dispatch('actionName') |
| Get computed state | this.$store.getters.getterName |
Key Takeaways
Always create and register the Vuex store before using it in your Vue app.
Use mutations to change state; never modify state directly.
Access state inside components with this.$store.state and update with this.$store.commit.
Actions handle async logic and commit mutations when ready.
Use getters to compute derived state from the store.