The Power Of Vuex In VueJs

Shubham Gupta
Mindful Engineering
5 min readJul 26, 2018
Photo by Paul Esch-Laurent on Unsplash

What is VueJS?

Vue. js is a progressive framework for JavaScript used to build web interfaces and one-page applications. Not just for web interfaces, Vue. js is also used both for desktop and mobile app development with the Electron framework.

If we creating a large scale application managing state in components can be difficult.

Vuex is Vue’s own state management pattern and library.

In this blog, we’ll look at why an application might need Vuex, and how it can make your app much better.

Why Should We Use Vuex in Vue App?

If you want to make your data centralize it is the correct time to use VueX.
Let’s see two practical examples

Bank Example

There is a bank with 5 working desks, we have a data centric STORE inside the bank. From any desk, we can access the data also we can update the data To STORE.

Real Example

If we have different components and have to display the same list of items data so it is better to save the list of items data into the Vuex Store that was easily accessible to all components in our app.

Access the data from STORE gives lots of advantages:

  • Easy to maintain the data and access from all components.
  • It reduced the repeated code required to save the data.
  • All data was saved in one place.
Photo by Arnold Francisca on Unsplash

“Let's Start With Some Code”

Step 1: Start with installing Vuex in your project.

npm install vuex --save

Step 2: Initialize the Vuex Store

Firstly have to create the Folder name store inside the root direct and create the file name index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {},
getters : {},
mutations: {},
actions : {}
})

Step 3: Give a way to connect the STORE with Vue app with main.js

import { store } from './store'new Vue({
el: '#app',
store,
router,
render: h => h(App)
})

How VueX Works?

State

Vuex uses a single state tree — that is, this single object contains all your application level states and serves as the “single source of truth.” This also means usually you will have only one store for each application. A single state tree makes it straightforward to locate a specific piece of state and allows us to easily take snapshots of the current app state for debugging purposes.

Getting Vuex State into Vue Components

// let's create a list component
const List = {
template: `<div>{{ list }}</div>`,
computed: {
list () {
return store.state.list
}
}
}

Whenever store.state.count changes, it will cause the computed property to re-evaluate, and trigger associated DOM updates.

const app = new Vue({
el: '#app',
store,
components: { List},
template: `
<div class="app">
<list></list>
</div>
`
})

Getters

One question arises in all minds how can our components and routes access the data stored in our state?

We define Getters inside our Vuex store which returns the data from our store back to our components. Let’s see how a simple Getter, to retrieve the name stored in our state looks like.

let yourGetterName= this.$store.getters.NAME

Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them:

computed: {
doneTodosList () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}

Mutations

As we learn above getters are used to get the data into the component, let’s see how we can set data into our state. We define setters, right? Except, Vuex setters are named slightly different. We define a Mutation to set data into our Vuex state.

mutations : {
SET_COUNTRY_CODE : (state,payload) => {
state.countryCode = payload,
}
}

What is a payload?

A payload is simply the data passed to our mutation from the component committing the mutation. How do we do that? Simple…

this.$store.commit(“SET_COUNTRY_CODE”,country_code)

Actions

Actions are similar to mutations, the differences being that:

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

Let’s register a simple action:

const store = new Vuex.Store({
state: {
list: 0
},
mutations: {
increment (state) {
state.list++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})

Dispatching Actions

store.dispatch('increment')

Take A Look With An Example

Let's create the index.js file with module users.

import Vue from 'vue'
import Vuex from 'vuex'
import users from "./modules/users"
Vue.use(Vuex)

export default new Vuex.Store({
modules: {
users
}
})

Now create the store that stores the relative information regarding the specific user.

const state = {
users: [],
posts: [],
comments: [],
user: [],
post: [],
comment: [],
};

Now create the getter methods that are used to get the data from store to different components.

const getters = {
allUsers: state => state.users,
allPosts: state => state.posts,
allComments: state => state.comments,
allUser: state => state.user,
allPost: state => state.post,
allComment: state => state.comment,
};

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous.

We are using a JSON placeholder to get the dummy data.

const actions = {

async getUsers({ commit }) {
const responce = await axios.get("https://jsonplaceholder.typicode.com/users")
commit("setUsers", responce.data)
},
async getPosts({ commit }) {
const responce = await axios.get("https://jsonplaceholder.typicode.com/posts")
commit("setPosts", responce.data)
}
};

To update the state in store we created the mutations:

const mutations = {
setUsers: (state, users) => (state.users = users),
setPosts: (state, posts) => (state.posts = posts)
};

It is necessary to export the store.

export default store

5 Important Takeaways

  1. state stored as a single large object.
  2. getters are used to access values/frequently used filters in the state.
  3. mutations modify the state. Remember that mutations are synchronous.
  4. actions are for asynchronous operations and multiple mutations
  5. Use the mapGetters / mapMutations / mapActions helper to simplify your code.

--

--