What is vuex?
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It integrates well with Vue's official devtools extension to provide advanced features such as zero-config time-travel debugging and state snapshot export/import.
What are vuex's main functionalities?
State Management
Vuex allows you to define a centralized state for your application and mutate this state in a controlled way using mutations.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
});
store.commit('increment');
console.log(store.state.count); // 1
Getters
Getters are like computed properties for stores. They can be used to compute derived state based on store state and are cached.
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done);
}
}
});
console.log(store.getters.doneTodos); // [{ id: 1, text: '...', done: true }]
Actions
Actions are similar to mutations, but instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state, payload) {
state.count += payload.amount;
}
},
actions: {
incrementAsync({ commit }, payload) {
setTimeout(() => {
commit('increment', payload);
}, 1000);
}
}
});
store.dispatch('incrementAsync', { amount: 10 });
Modules
Vuex allows you to divide your store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules.
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
Other packages similar to vuex
redux
Redux is a predictable state container for JavaScript apps, often used with React but can be used with any other JavaScript framework or library. It is similar to Vuex but has a different ecosystem and middleware support.
mobx
MobX is a state management library that is not restricted to React like Redux and provides a more flexible approach to state management based on observable data structures.
ngxs
NGXS is a state management pattern + library for Angular applications. It provides a similar centralized state management system to Vuex but is designed specifically for Angular's ecosystem.
akita
Akita is a state management pattern + library for Angular and React. It focuses on simplicity and sets up a store for managing the state of your application with less boilerplate than Redux or NGXS.