State Management with Vuex in Vue.js
Learn how to use Vuex for state management in your Vue.js application.
Introduction to Vuex
In this tutorial, we will learn how to use Vuex for state management in our Vue.js application. Vuex is the official state management library for Vue.js and it provides a simple and flexible way to manage global state.
Step 1: Installing Vuex
First, we need to install Vuex. 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 in the src directory:
// src/store.js
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 Application
Now, we can use the store in our application. We can do this by importing the store in our main.js file and using the mapState and mapActions helpers in our components:
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
// src/components/Counter.vue
<template>
<div>
<p>Count: {{ count }}</p>
<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? These paid resources pick up where this lesson leaves off.
Project-based vue.js video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked vue.js books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.