VueX State Management

Alaa Ahmed
3 min readAug 28, 2021

--

Introduction…

What is Vuex?

Core Concepts

How it works?

Introduction

Imagine you are developing a Vue application which are divided into smaller components ,Of course you can communicate between components using props either by sending them from parent to child or from child to parent using (emitting) concept , this would be great if the application has small scale and such communication won’t be over headache , but what if the application grow larger and each component would require to pass props to the parent of parent or vise versa to update values .. this would be over headache, so how we can handle such situation ? 😟

By using VUEX

What is VueX?

VueX is a state management library used for Vue applications which provides single source of truth to the application

Core Concepts:

State

Mutations

Actions

Getters

let’s talk about them in details.. 😉

👉 State:

  • Contains the Initial keys in the store
state: {
intialKey: [],
},

👉 Mutations:

  • State can be mutated or changed only through committing mutations.
  • Receive state as first argument and payload (holds the data to be updated) if any as second argument.
mutations: {
MutationName: (state, payload) => {
return (state.intialKey = payload);
}
},

Note: Mutations are synchronous.. so how to handle asynchronous requests? 😕

By using Actions

👉 Actions:

  • Unlike mutations, Actions are asynchronous so it handles asynchronous operations such as API calls
  • Commit mutations only
actions:{
ActionName: (context) => {
axios.get(`https://jsonplaceholder.typicode.com/photos`)
.then((res) => {
context.commit(MutationName, res);
}).catch((err) => console.log("err", err));
},
}

According to the example above ☝️ , actions takes context as a parameter which contains

This enables the action to:

  • access Initial values
  • Commit one or more mutation
  • Dispatch another action

👉 Getters:

  • Are like computed properties to get or access the keys in the state
getters: {
getterName: (state) => state.initialKey,
},

How it works?

  • Install vuex in project
npm install vuex --save
  • Create store file
  • Initialize State keys
  • Define Actions
  • Define Mutations
  • Finally set the getters
  • In your main file, initialize the store
  • In your component
  • Result 👏

References:

Vuex

--

--

Alaa Ahmed
Alaa Ahmed

No responses yet