SPA State Management - Vuex
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
Vuex helps us deal with shared state management with the cost of more concepts and boilerplate. It's a trade-off between short term and long term productivity.
Vuex Stores are reactive. Each change in the store will update the components that use that part of the data.
The state, the source of truth that drives our app;
The view, a declarative mapping of the state;
The actions, the possible ways the state could change in reaction to user inputs from the view.
The only way to actually change the State in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string type and a handler. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.
Actions are similar to mutations, the differences being that:
Instead of mutating the state, actions commit mutations.
Actions can contain arbitrary asynchronous operations.
Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.
this.$store.state.nameOfThing
this.$store.getters.nameOfThing
this.$store.commit('nameOfThing', payload)
this.$store.dispatch('nameOfThing', payload)
When a component needs to make use of multiple store state properties or getters, declaring all these computed properties can get repetitive and verbose. To deal with this we can make use of the mapState
helper which generates computed getter functions for us.
This is similar for mapGetters
, mapMutations
, mapActions
.
Alternatives
In Vue 3, Pinia is now the recommended state management solution. It offers a simpler and more intuitive API compared to Vuex, while still providing the core benefits of centralized state management.