💚 Vue.js Beginner

What is Vuex?

Answer

Vuex is Vue's official state management pattern and library (Flux/Redux-inspired) for managing global shared state. Core concepts: (1) State: single source of truth — the app's data: state: { users: [], loading: false }; (2) Getters: computed properties for the store — derived state: getters: { activeUsers: (state) => state.users.filter(u => u.active) }; (3) Mutations: synchronous functions that directly modify state — only way to change state: mutations: { SET_USERS(state, users) { state.users = users; } }. Commit: store.commit("SET_USERS", users); (4) Actions: handle async logic and commit mutations: actions: { async fetchUsers({ commit }) { const users = await api.getUsers(); commit("SET_USERS", users); } }. Dispatch: store.dispatch("fetchUsers"); (5) Modules: divide store into namespaced modules. Using in components: import { useStore } from "vuex"; const store = useStore(); store.state.users; store.getters.activeUsers; store.dispatch("fetchUsers"); store.commit("SET_USERS", []);. Vuex 4 works with Vue 3. Pinia is the successor: Vuex 5 was never released; Pinia (by the Vue team) is now the official recommended state management solution for Vue 3. Simpler API, no mutations (actions can mutate directly), better TypeScript support, and modular by default.