In this tutorial, we will explore the basics of Vuex, which is the official state management library for Vue.js. We will discuss the reasons why you should use Vuex and how to create a Vuex store. Additionally, we will go through a simple use case to understand how Vuex works.

Introduction to Vuex

Vuex is a state management library for Vue.js that allows you to share data across components in your application. While Vue.js provides options like props and events for component communication, Vuex is designed to handle more complex use cases by centralizing the application’s state in a single store.

Why Should You Use Vuex

Although there are other state management options like Redux, Vuex stands out as the official state management library for Vue.js. Its integration with Vue.js is seamless and eliminates the need to search for alternative solutions when starting a new project.

One of the key advantages of Vuex is its similarity to Redux, which follows the popular Flux pattern. If you are already familiar with Flux or Redux, Vuex will feel intuitive to you. Even if you are new to the concept, Vuex simplifies state management by providing a centralized store and allowing components to access it through getters.

Using Vuex introduces some complexity, but it solves the problem of unorganized props passing and event systems that can result in spaghetti code. If you find yourself spending a lot of time passing state around, Vuex can be a valuable tool.

Let’s Get Started

For this example, we will start with a Vue CLI application, which provides a more structured environment. You can also use Vuex by directly loading it into a script tag, but for larger applications, Vue CLI is the recommended approach.

To install Vuex locally, run npm install vuex or yarn add vuex in your project folder.

Creating the Vuex Store

To create a Vuex store, initialize Vuex and tell Vue to use it. Place the following code in a src/store/store.js file:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({})

This code sets up a Vuex store object using the Vuex.Store() API. We export the store to make it accessible throughout the application.

A Use Case for the Store

To demonstrate the usage of Vuex, let’s consider a scenario where we have two sibling components: one with an input field and another that displays the input field content. We want to update the second component whenever the input field value changes.

Introducing the New Components

First, we need to create the Form and Display components. Replace the HelloWorld component in your App.vue file with the following code:

<template>
  <div id="app">
    <Form/>
    <Display/>
  </div>
</template>

<script>
import Form from './components/Form'
import Display from './components/Display'

export default {
  name: 'App',
  components: {
    Form,
    Display
  }
}
</script>

Adding the State to the Store

Now let’s add the state to the store. Open the store.js file and define a state property in the store object. In this case, we’ll use the flavor property, which is initially an empty string.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    flavor: ''
  }
})

Adding a Mutation

In Vuex, the state can only be modified through mutations. We define a mutation called change that will be used inside the Form component to update the state.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    flavor: ''
  },
  mutations: {
    change(state, flavor) {
      state.flavor = flavor
    }
  }
})

Adding a Getter to Reference a State Property

Next, we need a way to access the state. We use getters to retrieve specific state properties. In this case, we define a getter for the flavor property.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    flavor: ''
  },
  mutations: {
    change(state, flavor) {
      state.flavor = flavor
    }
  },
  getters: {
    flavor: state => state.flavor
  }
})

Adding the Vuex Store to the App

We are now ready to use the store. In your main.js file, import the store and include it in the Vue application.

import { store } from './store/store'

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

By adding the store to the main Vue component, the store will be accessible in all Vue components through this.$store.

Updating the State on User Action using commit

To update the state when the user types into the input field, we use the store.commit() API. Add the following method to the Form component:

<template>
  <div>
    <label for="flavor">Favorite ice cream flavor?</label>
    <input @input="changed" name="flavor">
  </div>
</template>

<script>
export default {
  methods: {
    changed: function(event) {
      this.$store.commit('change', event.target.value)
    }
  }
}
</script>

In this example, we reference the store using this.$store and call the commit() method with the mutation name (change) and the value from the input field as the payload.

Using the Getter to Print the State Value

Finally, we need to display the state value in the Display component. Modify the template as shown below:

<template>
  <div>
    <p>You chose {{ $store.getters.flavor }}</p>
  </div>
</template>

In this template, we can access the getter using $store.getters.flavor.

Wrapping Up

Congratulations! You have learned the basics of using Vuex as the state manager for your Vue.js application. The full source code for this tutorial is available at https://codesandbox.io/s/zq7k7nkzkm.

While this tutorial covered the fundamentals of Vuex, there are still many concepts yet to be explored, such as actions, modules, helpers, and plugins. You can find more information on these topics in the official Vuex documentation.

Happy coding!