Vue js Vuex
Overview of Vuex in Vue
Vuex operates as a centralized layer where data logic resides. Instead of scattering shared state across unrelated components, Vuex maintains a unified memory space — ensuring predictable and consistent behavior across complex apps.
Why Use Vuex?
As applications expand, tracking data mutations and prop drilling becomes unmanageable. Vuex provides a structured approach to centralize, organize, and trace data flow, easing debugging and reducing duplication.
Core Segments of Vuex Store
Vuex revolves around five main sections:
- state – A single tree housing reactive properties accessible across the project.
- mutations – Functions strictly modifying the state synchronously.
- actions – For handling asynchronous operations and then committing mutations.
- getters – Functions to derive and compute values from the state.
- modules – Segments to organize large stores into smaller units.
Creating a Vuex Store
Below demonstrates how to set up a Vuex-powered application:
npm install vuex@next
Now define the store logic in a separate file, say store/index.js:
import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ } }, actions: { asyncIncrease(context) { setTimeout(() => { context.commit('increment') }, 1000) } }, getters: { doubled(state) { return state.count * 2 } } }) export default store Integrating Vuex with the App
Now connect the store in your main.js:
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
App.mount('#app')Using Vuex State and Actions in Components
Inside a Vue component, utilize the following approach:
<template>
<div>
<p>Counter: {{ $store.state.count }}</p>
<button @click="$store.commit('increment')">Add</button>
<button @click="$store.dispatch('asyncIncrease')">Add After Delay</button>
<p>Twice Value: {{ $store.getters.doubled }}</p>
</div>
</template>Advantages of Vuex Architecture
- Keeps component files cleaner by externalizing logic.
- Facilitates tracking and debugging via dev tools.
- Improves scalability with modular design patterns.
Modular Vuex
Vuex supports nested organization for large-scale structures:
const productsModule = {
state() {
return {
items: []
}
},
mutations: {
setItems(state, payload) {
state.items = payload
}
}
}
const store = createStore({
modules: {
products: productsModule
}
})Access with: this.$store.state.products.items
Conclusion
Vuex introduces a powerful method to control shared information, especially in complex Vue applications. Its separation of concerns and single source of truth make it ideal for maintaining large interfaces.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand VUE JS Tutorial visually:
What You'll Learn:
- 📌 Learn Vuex in 30 MINUTES! (Vue JS 3)
- 📌 STATE & STORE | VueJS & Vuex | Learning the Basics