State Management with Vuex Chapter 21
The main component of our Vuex application(s) is, therefore, the store, our single source of
truth across all component(s). The store can be read but not directly altered; it must have
mutation functions to carry out any changes. Although this pattern may seem strange at
first, if you've never used a state container before, this design allows us to add new features
to our application in a consistent manner.
As Vuex is natively designed to work with Vue, the store is reactive by default. This means
any changes that happen from within the store can be seen in real time without the need for
any hacks.
Thinking about state
As a thought exercise, let's start off by defining the goals for our application as well as any
state, actions, and potential mutations. You don't have to add the following code to your
application just yet, so feel free to read on, and we'll bring it all together at the end.
Let's start off by considering the state as a collection of key/value pairs:
const state = {
count: 0 // number
}
For our counter application, we just need one element of state—the current count. This will
likely have a default value of 0 and will be of type number. As this is likely the only state
inside of our application, you can consider this state to be application level at this point.
Next, let's think about any action types that the user may want to take our counter
application.
These three action types can then be dispatched to the store and thus we can perform the
following mutations, returning a new version of state each time:
Increment: Add one to the current count (0 -> 1)
Decrement: Remove one from the current count (1 -> 0)
Reset: Set the current count back to zero (n -> 0)
We can imagine that at this point, our user interface will be updated with the correct bound
version of our count. Let's implement this and make it a reality.