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';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 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
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['count'])
  },
  methods: {
    ...mapMutations(['increment', 'decrement']),
    ...mapActions(['incrementAsync'])
  }
}
</script>

Accessing State in Components

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

computed: {
  ...mapState(['count'])
}

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.

this.$store.commit('increment');

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.

this.$store.dispatch('incrementAsync');

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: {
  ...mapGetters(['getCount'])
}

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.