What Is Vuex in Vue.js?

Understanding Vuex in Vue.js

Vuex is a state management library for Vue.js applications. It provides a centralized store for managing the application state and allows components to communicate and share data in a predictable and efficient way. Here's an overview of Vuex along with code examples.

Installing Vuex

You can install Vuex using npm or yarn.

npm install vuex

Creating a Store

You define your Vuex store by creating a new instance of Vuex. Store and pass in an object that contains the store's state, mutations, actions, getters, and modules (if any).

// store.js
import Vue from 'vue';
import Vuex from 'vuex';


export default new Vuex.Store({
  state: {
    count: 0
  mutations: {
    increment(state) {
    decrement(state) {
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
      }, 1000);
  getters: {
    getCount: state => state.count

Using the Store in Components

You can access the Vuex store from Vue components using the mapState, mapMutations, mapActions, and mapGetters helpers, or by directly accessing this.$store.

// Counter.vue
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="incrementAsync">Increment Async</button>

import { mapState, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
  methods: {
    ...mapMutations(['increment', 'decrement']),

Accessing State in Components

You can access the state in components by mapping state properties to computed properties using the mapState helper.

computed: {

Committing Mutations

Mutations are synchronous functions used to update the store's state. You commit mutations using the commit method, which triggers a mutation with the specified mutation type.


Dispatching Actions

Actions are asynchronous functions used to perform side effects or async operations. You dispatch actions using the dispatch method, which triggers an action with the specified action type.


Accessing Getters

Getters are computed properties based on the store's state. You can access getters in components using the mapGetters helper or by directly calling this.$store.getters.

computed: {

This is a basic example of how to use Vuex in a Vue.js application. Vuex provides a powerful mechanism for managing state in large-scale applications and helps maintain a clear and predictable data flow.