Getting Started with Vuex
🎯 Introduction
In this article, you will learn to integrate Vuex into a Vue 2 project and use it to manage state. Understanding its core concepts, state and mutations, will help you avoid common mistakes and write more consistent, maintainable code. These foundations make state management easier to understand and work with.
🏷️ What Is State?
State is where Vuex stores application-level data.
It is reactive: changes automatically cause components that depend on it to re-render.
Think of it as a global data store where you can manage any data that components need to share.
State declared in a component's data belongs to that component, making it cumbersome to share across components. Vuex state addresses this problem.
🔧 What Is a Mutation?
Mutations are the prescribed way to change state in Vuex.
They are synchronous functions, which keeps state changes traceable.
To trigger a mutation, call the commit method.
This lets you track each state change in Vue Devtools, making debugging easier.
🚀 Using Vuex in a Vue 2 Project
Vuex is the official state management tool used with Vue 2 to centralize data shared by components in medium and large applications. Here is how to install, configure, and use it in a Vue 2 project.
Installing and Configuring Vuex in Vue 2
First, make sure you have a Vue 2 project set up. Then install Vuex with npm.
npm install vuex@3 --save
Once installed, import and register Vuex in your main entry file, usually main.js.
import Vue from 'vue';
import Vuex from 'vuex';
import App from './App.vue';
Vue.use(Vuex);
const store = new Vuex.Store({
// We will fill this in below
});
new Vue({
el: '#app',
store, // Inject the store
render: h => h(App),
});
Creating the Store and State
The store is the central Vuex instance. It contains global state, mutations, actions, and more.
When creating the store, define state to hold shared data.
const store = new Vuex.Store({
state: {
count: 0,
isLoggedIn: false,
},
mutations: {
increment(state) {
state.count++;
},
login(state) {
state.isLoggedIn = true;
},
},
});
Here, we define two state variables and their corresponding mutations.
Reading State in Components
Any component can access state through this.$store.state.
<template>
<div>
<p>Current count: {{ count }}</p>
<p>Logged in: {{ isLoggedIn }}</p>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count;
},
isLoggedIn() {
return this.$store.state.isLoggedIn;
},
},
};
</script>
The component's view now updates automatically when state changes.
Updating State by Committing Mutations
State changes must go through mutations rather than direct assignments.
<template>
<div>
<button @click="incrementCount">Increment count</button>
<button @click="loginUser">Log in</button>
</div>
</template>
<script>
export default {
methods: {
incrementCount() {
this.$store.commit('increment');
},
loginUser() {
this.$store.commit('login');
},
},
};
</script>
⚠️ Common Pitfalls and Tips
Always use mutations to change state so that changes remain traceable. The following direct assignment is incorrect:
this.$store.state.isLoggedIn = true;
actions, where you can use commit to trigger mutations.Vue Devtools lets you inspect mutation calls and state updates in real time, making it a useful tool for monitoring Vuex state changes.
❓ Knowledge Check
Q1: Is Vuex state defined in a component's data?
No. It is global state defined in the Vuex store. Components access it through this.$store.state.
Q2: Why should you avoid changing state directly?
Direct changes bypass mutation tracking. Vuex uses mutations to keep state changes predictable and debuggable.
Q3: How do you handle asynchronous operations?
Put asynchronous operations in actions, which can commit mutations to update state synchronously.
🧪 Practice
Exercise 1
Create a Vuex store in a Vue 2 project, define a todos array in state, and write a mutation to add a new task.
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
todos: [],
},
mutations: {
addTodo(state, todo) {
state.todos.push(todo);
},
},
});
<template>
<div>
<ul>
<li v-for="(todo, index) in todos" :key="index">{{ todo }}</li>
</ul>
<button @click="addNewTodo">Add task</button>
</div>
</template>
<script>
export default {
computed: {
todos() {
// Write your code here
},
},
methods: {
addNewTodo() {
// Write your code here
},
},
};
</script>
🎉 You now know how to install and configure Vuex, manage state, commit mutations, and avoid common pitfalls! With these foundations, you can start managing complex state in Vue 2 projects while keeping your code consistent and maintainable. Keep building your frontend skills!
Why Use Vuex?
Learn why state management matters by exploring the challenges of component communication, what Vuex provides, and when to use it.
Understanding Vuex Core Features
Explore getters, actions, and mutations in Vuex, and learn why synchronous state changes and asynchronous operations have separate responsibilities.
