Vue.js with Vuex: State Management Patterns

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

Core Concepts

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

<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.

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.