Using Vuex to Manage State in a Vue.js App
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
Learn how to use Vuex to manage state in a Vue.js app and keep your components in sync.
Introduction to Vuex
Vuex is the official state management library for Vue.js. It allows us to manage state in a centralized store and keep our components in sync. In this tutorial, we will learn how to use Vuex to manage state in a Vue.js app.
Step 1: Installing Vuex
First, we need to install Vuex in our project. We can do this by running the following command in our terminal:
npm install vuex
Step 2: Creating the Store
Next, we need to create the store. We can do this by creating a new file called store.js and defining our state, mutations, and actions:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
}
})
export default store
Step 3: Using the Store in Our Components
Finally, we need to use the store in our components. We can do this by using the mapState and mapActions helpers:
<template>
<div>
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: mapState(['count']),
methods: mapActions(['increment'])
}
</script>
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based vue courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for vue books — check the publication year so the examples match current versions.
Search Amazon →