What’s Vuex

Vuex is a pattern based on Flux, Redux, and the Elm Aarchitecture. One of the good things of Vuex is it’s maintained by the Vue team, so they work perfectly together.

The objective of Vuex is to provide predictable state management with a centralized store for all the components in your application. It enforces the usage of some rules in order to manage the state, which also helps to provide a better structure and maintainability for our code.

Vuex key concepts

Let’s go through some of the key concepts you have to understand when you’re using Vuex (we’re also going to see most of them later in code examples).

Vue components

Your components can use the global store state of your application and also have their own state. Any information you’re going to need in multiple components should be in the store state.

In order to have access to the store on all your components, you need to add it to your root component.

Store state

You have to initialize the properties of the state of your application when you declare your store.

Change the store state

There are two ways to change the store state from your components.

Commit mutations

Mutations are operations to our state managed by our store. You can’t execute them directly from your components. In order to execute a mutation, you have to use the store commit method, which receives the name of the mutation to execute and may receive an object containing custom data. Mutations are synchronous.

Mutations are operations to our state managed by our store. You can’t execute them directly from your components. In order to execute a mutation, you have to use the store method, which receives the name of the mutation to execute and may receive an object containing custom data. Mutations are synchronous. Dispatch actions

Your store may also contain actions. In order to execute an action from your components, you have to execute the dispatch method of the store. This method also receives the name of the action to dispatch and an object containing custom data. Actions end up committing mutations, they don’t change the state directly. Actions can be asynchronous and can return promises.

The main reason for the existence of actions and mutations is for separations of concerns between synchronous and asynchronous operations.

When the store state changes any component its using that part of the state is going to react and update.

Store getters

They’re like computed properties for your store. A getter’s result is cached based on its store state dependencies and will only reevaluate when some of its dependencies have changed.

Store modules

As your application grows, a single declaration of your store can get really messy. In order to deal with this, you can divide your store into modules — each of them can contain all the store features. Finally, you can add all these modules to your store declaration.

Let’s see some example now.