This guide will help you understand the basics of Vuex, a state management pattern + library that serves as a centralized store for all the components in an application. Vuex is widely used with Vue.js to manage state across components.

What is Vuex?

Vuex is a pattern + library for managing state in Vue.js applications. It serves as a centralized store for all the components in an application, providing a way to react to state changes in a predictable way.

Key Features

  • Centralized State: Vuex makes it easier to manage state across components.
  • Reactivity: Vuex ensures that components react to state changes.
  • Mutations: Changes to the state are made through mutations, which are predictable and easy to track.
  • Actions: Complex logic can be handled in actions before mutations are committed.

Getting Started

To get started with Vuex, you first need to install it in your Vue.js project. You can do this by running the following command:

npm install vuex --save

Once installed, you can create a new Vuex store in your project.

Store Structure

A Vuex store is an object that contains the state, mutations, actions, and getters. Here is an example of a simple Vuex store:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment(context) {
      context.commit('increment');
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
});

Using Vuex in Components

To use Vuex in a component, you need to inject the store into the component. You can do this by using the mapState helper function.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

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

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

More Resources

For more information on Vuex, you can visit the official Vuex documentation.

Vue.js Vuex