Vuex in a nutshell

Vuex is a state management solution that is tailored specifically for Vue applications. As mentioned, it is inspired by Flux. You can use Vuex as a centralized store for the state, which is shared between components of your application. It has rules to ensure that the state can only be changed in a predictable way.

As you can see in Figure 11.1, in Vuex data flows in one direction. Usually, it starts from a Vue component, which dispatches an action that can commit a mutation and only the mutation can make changes to the state, which live inside a store. The store is the center of every Vuex application. Different from localData we saw earlier, Vuex stores are reactive. That is, the changes made to the store through a mutation will be synced to the Vue component through the reactivity system of Vue.js:

Figure 11.3: Vuex overview (source: https://vuex.vuejs.org)

Besides committing mutations, actions can also communicate with the backend API or make arbitrary asynchronous operations before committing mutations. Through mutations, a Vuex application can integrate with Vue.js DevTools to provide advanced features such as time-travel debugging and state snapshot export/import.

In Vuex, the state is a single object that contains all of our application-level state. It serves as the single source of truth. Usually, we will only create one store for each Vue application to hold the state. Putting all of the state of the application in one single object can bloat the store as our application grows. To solve this issue, Vuex provides support for modularity. It allows us to divide our store into modules and each module can contain its own state. We will see how that works later in this chapter.

Besides state, actions, mutations, and modules, Vuex also provides getters. These are useful when we need to compute the derived state based on the store state. For example, if we put all of the messages in the store, we can create a getter to calculate the number of unread messages. You can think of Vuex's getters as computed properties for stores. We will see how that works later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.153.212