Vuex Mapstate Module

Posted on  by admin
Vuex uses a single state tree - that is, this single object contains all your application level state and serves as the "single source of truth."

This also means usually you will have only one store for each application. A single state tree makes it straightforward to locate a specific piece of state, and allows us to easily take snapshots of the current app state for debugging purposes.

The single state tree does not conflict with modularity - in later chapters we will discuss how to split your state and mutations into sub modules.

The data you store in Vuex follows the same rules as the data in a Vue instance, ie the state object must be plain.

See also:Vue#data.

So how do we display state inside the store in our Vue components?

Since Vuex stores are reactive, the simplest way to "retrieve" state from it is simply returning some store state from within a computed property:.

Whenever store.state.count changes, it will cause the computed property to re-evaluate, and trigger associated DOM updates.

However, this pattern causes the component to rely on the global store singleton.

When using a module system, it requires importing the store in every component that uses store state, and also requires mocking when testing the component.

Vuex "injects" the store into all child components from the root component through Vue's plugin system, and will be available on them as this.$store.

Let's update our Counter implementation:. When a component needs to make use of multiple store state properties or getters, declaring all these computed properties can get repetitive and verbose.

import { mapState } from 'vuex';

To deal with this we can make use of the mapState helper which generates computed getter functions for us, saving us some keystrokes:.


Not the answer you're looking for? Browse other questions tagged javascriptvue.jsaxiosvuex or ask your own question.