Vue.js with Vuex: State Management Patterns

On this page

Vuex is Vue’s official state management library. When your app grows beyond simple component state, Vuex brings order to the chaos.

Core Concepts

JavaScript19 lines
const store = new Vuex.Store({
  state: {
    count: 0,
    todos: []
  },
  mutations: {
    INCREMENT(state) { state.count++; },
    ADD_TODO(state, todo) { state.todos.push(todo); }
  },
  actions: {
    async fetchTodos({ commit }) {
      const todos = await api.getTodos();
      todos.forEach(t => commit('ADD_TODO', t));
    }
  },
  getters: {
    completedTodos: state => state.todos.filter(t => t.done)
  }
});

In Components

VUE12 lines
<script>
import { mapState, mapActions } from 'vuex';
export default {
  computed: {
    ...mapState(['todos', 'count'])
  },
  methods: {
    ...mapActions(['fetchTodos'])
  },
  created() { this.fetchTodos(); }
};
</script>

When to Use Vuex

  • Shared state across many components
  • Need for time-travel debugging
  • Complex state transitions

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.