Vue 2 Tutorial- Vue 2 Vuex State Management Example

Vue is an excellent open-source front-end library to build user-friendly web/mobile applications. It follows the same component-based architecture as other popular frameworks do.

In this tutorial, we will understand how to manage the state when the size of the application starts expanding. We have to assume that we have more than 100 components or more than that and we have to manage the data that goes from one component to another component.

 

So, Vue offers the Vuex State Management Library that does the job for us. In this Vue guide, we will understand how we can work with the Vuex library to manage the state via the store.

 

Let’s see now what we will be covering in this Vue tutorial:

  • Vuex State Management Example For Vue.js
  • Setup Vue + Vuex
  • Create JSON Server
  • Creating & Managing State Via Vuex Store
  • Adding Vuex Store In Vue Component
  • Conclusion

 

Step 1- Vuex State Management Example For Vue.js

In order to setup a Vuex Store to manage the states among Vue components, we need to create a basic app in which we will make the API call to fetch components from the fake json server and store the products in the Vuex store.

 

Step 2- Setup Vue And Vuex

We need to install node and Vue CLI in our development system for moving further. We will be running the below command to create a new vue.js project:

vue create vue-state-mgmt

 

We can automatically configure the Vuex store by choosing the option at the time of installing the fresh new Vue app.

 

If we select Vuex, then the Vuex store will be set up by default with the Vue app:

Configure Vuex Store in Vue

 

Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

 

To remove the above error for invoking the app, we have to make sure to update the “scripts”: [] array in the package.json file:

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

 

Step 3- Create JSON Server

We need to setup a fake JSON server in order to make the API calls.

We have to type the following command in the terminal to install the JSON-server:

npm install -g json-server

 

Then, we will create the database.json file at the root of the project and also populate some data into it:

{
    "users": [
        {
            "id": 1,
            "name": "Leanne Graham",
            "email": "Sincere@april.biz"    
        },
        {
            "id": 2,
            "name": "Ervin Howell",
            "email": "Shanna@melissa.tv"
        },
        {
            "id": 3,
            "name": "Clementine Bauch",
            "email": "Nathan@yesenia.net"
        }        
    ]     
}

 

Now, we will start the JSON server:

json-server --watch database.json

 

Step 4- Creating & Managing State Vie Vuex Store

We can create a store by creating an instance of Vuex’s store and passing in our store details as objects:

The Vuex library offers a centralized store for managing the state of Vue.js components. It is responsible for getting and updating the state of every value which are declared using the Vuex library.

then, we have to create the modules/user-module.js file and paste the below code into it:

import axios from 'axios'
const state = { 
    users: []
};
const getters = { 
    usersList: state => state.users
};
const actions = { 
    async fetchUsers({commit}){
      const response = await axios.get("http://localhost:3000/users");
      commit("setUsers", response.data)
    },
    async addUsers({commit}, user){
      const response = await axios.post("http://localhost:3000/users", user);
      commit("addNewUser", response.data)
    },
    async deleteUser({commit}, id){
      await axios.delete(`http://localhost:3000/users/${id}`);
      commit("removeUser", id)
    }
};
const mutations = { 
    setUsers: (state, users) => (
        state.users = users
    ),
    addNewUser: (state, user) => state.users.unshift(user),
    removeUser: (state, id) => (
        state.users.filter(user => user.id !== id),
        state.users.splice(user => user.id, 1)
    )
};
export default {
    state,
    getters,
    actions,
    mutations
}

 

Afterward, we import the userModule in the store/index.js file:

import Vue from 'vue'
import Vuex from 'vuex'
import UsersModule from '../store/modules/users-module'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    UsersModule
  }
})

 

state: Vuex manages a single state tree-this single object includes all our application-level states and serves as the “single source of truth”. this also means usually, we will have only one store for each application.

getters: Vuex allows us to define “getters” in the state. They work as a computed property for stores. With the same computed properties, a getter’s outcome is cached based on its dependencies, and will solely re-evaluate when some of its dependencies have changed.

actions: The action handlers are used to make API calls that are used to perform the CRUD operations to manage the data for the Vuex store. Action handlers get a context object which reveals the same set of methods and properties on the Vuex store instance.

mutations: As the name suggests, it is responsible for mutating the state of the store object, we can easily update the Vuex state. The whole approach to updating the state in a Vuex store is by performing a mutation. Vuex mutations are related to events: each mutation has a string type and a handler.

 

Step 5- Adding Vuex Store In Vue Components

In this step, we will add the Vuex store in Vue components and manage the data in Vue store.

Then, we will add the below code inside the components/AddUser.vue file:

<template>
 <form @submit.prevent="onUserSubmit">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Enter name" v-model="name">
  </div>
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Enter email" v-model="email">
  </div>
  <button type="submit" class="btn btn-block btn-primary">Add</button>
</form>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: 'AddUser',
  data(){
      return {
        name: '',
        email: ''
      }
  },
  methods:{
    ...mapActions(["addUsers"]),
    onUserSubmit() {
        this.addUsers({
          name: this.name,
          email: this.email
        })
    }
  }
}
</script>

 

let’s now display the users’ list in the Vue component. We have to include the below code inside the components/Users.vue:

<template>
  <div>
    <ul class="list-group mt-5">
      <li class="list-group-item list-group-item-action" v-for="user in usersList" :key="user.id">
        <div class="d-flex w-100 justify-content-between">
          <h3>{{user.name}}</h3>
          <small class="text-danger delete" @click="deleteUser(user.id)">✕</small>
        </div>
        <p>{{user.email}}</p>
      </li>
    </ul>
  </div>
</template>
<script>
  import {
    mapGetters,
    mapActions
  } from "vuex";
  export default {
    name: 'Users',
    methods: {
      ...mapActions(["fetchUsers", "deleteUser"])
    },
    computed: mapGetters(["usersList"]),
    created() {
      this.fetchUsers()
    }
  }
</script>
<style>
 .delete {
   font-size: 18px;
   cursor: pointer;
 }
</style>

 

mapGetters: it’s a helper that allows formulating a computed property that displays the value returned by an assigned getter.

mapActions: It’s a helper that allows defining a method that would be comparable to calling dispatch on an action.

mapMutations: it’s a helper that helps create a method that will be similar to calling commit on a mutation.

Adding Vuex Store in Vue Components

 

Conclusion

So, in this Vue tutorial, we have tried to understand the state management concept. We have seen how to create a Vuex store that manages the data via state, getters, mutations and actions for the Vue components.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *