Vue JS State Management using Vuex Store Tutorial

Vue JS state management tutorial; in this guide, we are going to discuss the significant topic, state management in vue; we will explain how to manage state in Vue js using the Vuex state management pattern.

We all are aware of the Vue prodigy; the proliferation of tis features is endless. It is a widely used framework that helps you build enterprise-level app’s frontend without moving heaven and earth.

Today, in this tutorial, we will understand what vue state management is and how it works. Ideally, we will persuade you how to handle state in vue, in association with Axios HTTP requests.

An application is built with multiple components; every component has a different role to play; seldom, one component might rely on another component. Actions from different views may need to mutate the same piece of state.

The vue store gets aligned with the Vue browser tool, and you can get the tool from here.

Vue State Management with Vuex Example

  • Step 1: Set Up Vue CLI
  • Step 2: Create Vue Project
  • Step 3: Install Axios HTTP Client
  • Step 4: Create and Register New Components
  • Step 5: Build Fake REST API
  • Step 6: Use Vuex Store in Vue
  • Step 7: Get Vuex State into Vue Components
  • Step 8: Start Vue Application

Set Up Vue CLI

First, the section guides you on installing the vue cli package, and it allows you to use the vue command in your command prompt.

npm install -g @vue/cli

Create Vue Project

We assume you have already created the vue project but if not then execute the following command.

vue create vue-cosmic-app
cd vue-cosmic-app

Install Axios HTTP Client

Axios lets you make HTTP requests, and we particularly need this package to make HTTP requests and handle through vue store management pattern.

npm install vue-axios axios

The significance of this library is only when you inject it into the src/main.vue file.

import Vue from 'vue'
import App from './App.vue'

import VueAxios from 'vue-axios'
import axios from 'axios'

Vue.use(VueAxios, axios)


new Vue({
  render: h => h(App)
}).$mount('#app')

Create and Register New Components

To share state between components requires creating new components; let us create Create.vue and List.vue in the components folder.

Update code in Create.vue file.

<template>
    
</template>

<script>
    export default {
        data() {
            return {            
            }
        },
        mounted() {
        }
    }
</script>

Update code in List.vue file.

<template>
    
</template>

<script>
    export default {
        data() {
            return {            
            }
        },
        mounted() {
        }
    }
</script>

Moreover, add both the components in the src/App.vue file.

<template>
  <div class="container mt-5">
    <Create />
    <List />
  </div>
</template>

<script>
  import Create from './components/Create'
  import List from './components/List'

  export default {
    name: 'App',
    components: {
      Create,
      List
    }
  }
</script>

Build Fake REST API

JSON server is the package we are dying to install, and this allows creating test apis, although this prodigy is not recommended when you have your apis.

npm install json-server

Go to the root of the project, create backend/db.json file, than put all the code inside this file.

{
  "todos": [
      {
          "id": 1,
          "title": "Create a source of truth"
      },
      {
          "id": 2,
          "title": "Inspire conversation"
      }     
  ]     
}

Use command in command prompt to run the json-server in vue.

json-server --watch backend/db.json --port 8888

Use Vuex Store in Vue

Next, we create the confluence of vuex store in vue, in the src directory create a new folder store, inside this folder create modules folder and index.js file respectively.

Next, open store/index.js file, import TodoModule, Vuex, inject Vuex in .use() method, and define the state properties in Vuex.Store({...}) object.

import Vue from 'vue';

import Vuex from 'vuex';
import TodoModule from '../store/modules/todo-module';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  },
  modules: {
    TodoModule
  }
})

For state management, we used the state, getters, actions, and mutations in the Vue store template, alongside we align HTTP requests with the Vuex store.

Update code in modules/todo-module.js file.

import axios from 'axios'


const state = { 
    todos: []
};

const getters = { 
    todosList: state => state.todos
};

const actions = { 
    async getTodos({commit}){
      const res = await axios.get("http://localhost:8888/todos");
      commit("setTodo", res.data)
    },

    async createTodo({commit}, todo){
      const res = await axios.post("http://localhost:8888/todos", todo);
      commit("addTodo", res.data)
    },

    async deleteTodo({commit}, id){
      await axios.delete(`http://localhost:8888/todos/${id}`);
      commit("removeTodo", id)
    }
};

const mutations = { 
    setTodo: (state, todos) => (
        state.todos = todos
    ),
    addTodo: (state, todo) => state.todos.unshift(todo),
    removeTodo: (state, id) => (
        state.todos.filter(res => res.id !== id),
        state.todos.splice(res => res.id, 1)
    )
};

export default {
    state,
    getters,
    actions,
    mutations
}

Next, head over to the src/main.js file and import the store option similarly inject into the Vue instance; this way, the store will be available to all the child components.

import Vue from 'vue'
import App from './App.vue'

import 'bootstrap/dist/css/bootstrap.min.css';

import VueAxios from 'vue-axios'
import axios from 'axios'
Vue.use(VueAxios, axios)

// import store
import store from '../store'


new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

Get Vuex State into Vue Components

In this section, we will use the mapActions, mapGetters, and mapMutations helpers to call the function or methods to handle the state in vue.

Open and update the components/Create.vue file.

<template>
 <form @submit.prevent="onSubmit">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Whta's in your mind" v-model="title">
  </div>
  <button type="submit" class="btn btn-block btn-danger">Create Todo</button>
</form>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: 'Create',
  data(){
      return {
        title: ''
      }
  },
  methods:{
    ...mapActions(["createTodo"]),
    onSubmit() {
        this.createTodo({
          title: this.title
        })
    }
  }
}
</script>

Open and update the components/List.vue file.

<template>
  <div class="mt-4">
      <div v-for="todo in todosList" :key="todo.id">
          <h3>{{todo.title}}</h3>
          <span class="remove" @click="deleteTodo(todo.id)"> Remove </span>
      </div>
  </div>
</template>

<script>
  import { mapGetters, mapActions } from "vuex";

  export default {
    name: 'List',
    methods: {
      ...mapActions(["getTodos", "deleteTodo"])
    },
    computed: mapGetters(["todosList"]),
    created() {
      this.getTodos()
    }
  }
</script>

<style>
    .remove {
        font-size: 20px;
        cursor: pointer;
        color: red;
    }
</style>

Start Vue Application

In the final step, we start the app through the terminal, and to check your app locally, use the mentioned below url.

npm run serve
http://localhost:8080

Vue JS State Management

Conclusion

Especially when you are creating a large SPA, chances are you might face a similar problem we are talking about. Vuex offers a predefined mechanism that handles shared states pretty quickly with its robust pattern.

In this guide, we explained the state in vue; most importantly, we showed you how to visualize the fidelity of Vuex for eloquent state management in vue.