VueJs with vuex — for absolute beginners

Unni Krishnan D
5 min readMar 10, 2019

For every single page application there must be a store for optimal way of data sharing between components.For Reactjs we have redux/flux and for Angular we have ngrx. For Vuejs we have vuex.

Before you proceed you should have a basic understanding of Vuejs or at least the concept about Model–view–viewmodel (MVVM).We will be having components ,views and styles like every SPA frameworks.Ill be covering vuex from scratch so no prior knowledge in vuex is required.

What is a store ?

A store as for every single page application is a single point of truth(simply data).It provides API’s for modifying the data in the store. Vuex is a state management pattern and library for Vuejs applications. It serves as a centralized store for all the components in an application.

Installation of vuex

Assuming you have a base vuejs application.Simply execute this command within the project.

npm install vuex

Structure of Vuex store

In the root folder of your application create this file and name it as store.js

import Vuex from ‘vuex’
import Vue from ‘vue’
Vue.use(Vuex)export default new Vuex.Store({state: {},getters:{},mutations: {},actions:{}})

And in this main.js file where all the bootstrapping is done add this line where store is the store.js file

import store from ‘./store’

and in the bootstrapping section

new Vue({store, /** Add this line **/render: h => h(App),}).$mount(‘#app’)

Now we have successfully imported store in our application.Lets go through the different sections in the store.js

state : It holds all the data for our application.We can even set the initial state of data here for example

state: {
userlist : [],
showpopup :false,
listdata : [],
},

getters : Computed properties of data is stored here.For example we want to get the count of all users in the store.Simply write

getters:{
totalUsers : state => { return state.userlist.length },
}

mutations: Functions to manipulate store is written here.We will come to that later in detail.

actions : Actions are similar to mutations, the differences being that:

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.

Now lets move to our application and what we are trying to achieve.Our application on initial load (more specifically on load of a component) will fetch some data from an API and stores it in the vuex store.We read the same data from the store and do all the manipulations with it.

The API part

import axios from 'axios'export default {getUsers(){return axios.get('/users').then(response => {return response.data;})
}
}

Name the file as UserApi.js.we are using axios for API calls and dont forget to add this line in main.js


axios.defaults.baseURL = ‘https://jsonplaceholder.typicode.com'

so the url will be https://jsonplaceholder.typicode.com/users

The component part

// Import the above API file in your component
import UserApi from ‘../services/UserApi’

Lets call this API in the created life cycle hook of vuejs

created() { // this is a life cycle hookUserApi.getUsers().then(users => {this.addUser(users); //we will come to this function later}).catch().finally(() => {})}

Now we have to use helper functions of vuex to retrieve and set data from store.
In our component we have to import this

import { mapMutations, mapState, mapGetters} from ‘vuex’

These helpers are used to map store with components (mutations,state and getters)

Lets get back to our store.js and add our mutations,getters and states

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({state: {users:[] // we are displaying a list of users},getters:{
//getter for total number of users
totalUsers : state => {return state.users.length },
//getter for getting the Max id from the user list ,The user list is a JSON and it has a field id.
maxId : state => {return Math.max(...state.users.map(o => o.id), 0) + 1;}},mutations: {
//Add user to the existing array
ADD_USER:(state,name) =>{state.users.push(...name);},
//Remove user from the user list
REMOVE_USER:(state,index) =>{state.users.splice(index,1);},},actions:{//we dont have any actions for this example}})

Again in our component and in the life cycle hook computed add this

computed: {...mapState([     'users' // this is the variable we are initializing in the state section of store
]),
...mapGetters([
// The getter function names
'maxId',
'totalUsers'
])
},

Again in our component and in the life cycle hook methods add this

methods: {
//The name of functions in the mutation section in the store.js
…mapMutations([
‘ADD_USER’,
‘REMOVE_USER’,
]),
}

Now we have added all the code related to store.js. Now its time to call and utilize them.Previously we had UserApi which calls the API on page load.We are storing the response in our store.

created() {UserApi.getUsers().then(users => {this.addUser(users);//This function adds the API result to our store}).catch().finally(() => {})},
methods() {
addUser:function(data){
// data is coming from API
// ADD_USER is a mutation function.It is now available for calling // because we have used mapMutations to bind that with component this.ADD_USER(data)
}
}
User API data

Binding the store data with template


<div v-for=”(user,index) in users” class=”row” v-bind:key=user.id>
<div> {{ user.name }} </div><div> <a :href=’”mailto:”+user.email’>{{ user.email }}</a> </div><div> {{ user.phone }} </div><div> {{ user.website }} </div><span v-on:click=”removeUser(index)” class=”link”>delete</span></div>

Use of getters


<p>Total users in store : <strong>{{this.totalUsers}}</strong></p>

we had mapGetters in our application.simply call that getter function.

Manipulations of store

Removing an user from store

removeUser(id){this.REMOVE_USER(id)},

Adding an user to the store

<button v-on:click="addUserInput">Add</button>addUserInput(){this.addUser([{
“id”: this.maxId, // again a getter function
“name”: this.username,
“phone”:this.phone,
“email”:this.email,
“website”:this.website,
}])
this.username = ''
this.phone = ''
this.email = ''
this.website = ''
},
addUser:function(data){
this.ADD_USER(data)
}

Finally lets go through the steps once again

  1. Initialize store with respective getters,mutations and state
  2. On load of the component call the API,on success of it store the data in our vuex store by passing the data to a mutation function.Use mapMutations to call mutation function from a component
  3. Use getters wherever necessary.
  4. Implement the same for ADD and DELETE functionality.
  5. Bind store variables to components using mapState.

Screenshot

The complete example can be found here
https://github.com/ubercooluk/vuex-example

just clone the repo. Then all you have to do is

 yarn install
yarn serve

Conclusion
We have gone through vuex store,helper functions in store and finally how to communicate between store and components and use a single ,manageable source of data for our application.

--

--