Vuex: Centralized state management with example

Deepak Ranolia
2 min readApr 4, 2023

--

In Vue 3, you can use the latest version of Vuex to implement centralized state management in your Vue.js applications. Here’s an example of how to use Vuex for centralized state management in Vue 3:

import { createApp } from 'vue'
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
tasks: []
}
},
mutations: {
addTask(state, task) {
state.tasks.push(task)
},
removeTask(state, taskId) {
state.tasks = state.tasks.filter((task) => task.id !== taskId)
},
},
actions: {
fetchTasks(context) {
// Call an API to fetch the list of tasks
const tasks = [{ id: 1, title: 'Task 1' }, { id: 2, title: 'Task 2' }]
// Commit a mutation to update the state with the fetched tasks
context.commit('addTasks', tasks)
},
},
})
const app = createApp({
// your app component
})
app.use(store)app.mount('#app')

In this example, we’ve defined a Vuex store with a state object that includes a list of tasks. We’ve also defined mutations to add and remove tasks from the list, and an action to fetch tasks from an API and commit a mutation to update the state with the fetched tasks.

To use this store in our Vue.js application, we can simply import the store and use it in our components, like this:

javascriptCopy code
import { defineComponent } from 'vue'
import { useStore } from 'vuex'
export default defineComponent({
methods: {
addTask(task) {
this.$store.commit('addTask', task)
},
removeTask(taskId) {
this.$store.commit('removeTask', taskId)
},
fetchTasks() {
this.$store.dispatch('fetchTasks')
},
},
})

In this example, we’ve used the useStore hook to access the store in our component and defined methods to call the mutations and actions defined in the store.

By using Vuex for centralized state management, we can easily manage and update the state of our application in a predictable and maintainable way

BONUS BELOW

If you are new to the web development and hustling for bread and butter due to low income, Please check out the below link
Live Chat Jobs — You have to try this one at home

--

--

Deepak Ranolia
Deepak Ranolia

Written by Deepak Ranolia

Strong technical skills, such as Coding, Software Engineering, Product Management & Finance. Talk about finance, technology & life https://rb.gy/9tod91

No responses yet