Vuex is a double-edged sword. If used properly, it can make your life a lot easier when working with Vue. It can also make a mess of your codebase if you’re not careful.

There are four main concepts you shouldunderstand before you use Vuex: state, getters, mutations, and actions. A simple Vuex state manipulates data within these concepts in the store. Mapping in Vuex provides a nice, clean way of retrieving data from them.

In this tutorial, we’ll demonstrate how to map data from the Vuex store. If you’re a Vue developer who’s familiar with the basics of Vuex, these best practices will help you write cleaner and more maintainable code.

This tutorial is targeted an average Vue.js developer who knows the basics of Vue.js and Vuex. who is on a quest to write cleaner and maintainable code using best practices.

What is mapping in Vuex?

Mapping in Vuex enables you to bind any of the state’s properties (getters, mutations, actions, state) to a computed property in a component and use data directly from the state.

Below is an example of a simple Vuex store with test data in state.

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    data: "test data"
  }
  }
})

If you want to access the value of data from the State, you can do the following in your Vue.js component.

computed: {
        getData(){
          return this.$store.state.data
        }
    }

The above code works but quickly gets ugly as data in the state starts to grow.

For example:

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {
        id:1,
        age:23,
        role:user
        data:{
          name:"user name",
          address:"user address"
        }
    },
    services: {},
    medical_requests: {},
    appointments: {},
    }
  }
})

To get the username from the user object in state:

computed: {
        getUserName(){
          return this.$store.state.user.data.name
        }
    }

This will get the job done, but there is a better way.

#vue #vuex #javascript #web-development

A Complete Guide to Mapping in Vuex
2.15 GEEK