Managing state in Vue.js with Vuex

Daan
ITNEXT

--

In a large Vue application it is inevitable that you run into the problem of different components having to use the same variable. To make this work you often have to pass the same variable between a lot of components. Variables are being passed from component to component all the way down the tree, which makes your code an unreadable mess. If you continue with this long enough, you will reach a certain point where managing state gets very complex.

Vuex

The solution, ofcourse, is Vuex. Vuex is a state management library for Vue.js applications. At the center of every Vuex application is a store, which basically is a container that holds the state of the application.

When using Vuex, components use the same data source. This means that there is a single source of truth. Without Vuex, components could have their own version of state.

In this article I will show you how to setup a Vuex store and how you can use this store within the Vue components. I will be starting from scratch with a new Vue project.

Installation

To use Vuex within our Vue application we have to install it first:

npm install vuex --save

--

--