State

Single State Tree

Try this lesson on Scrimba

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#dataState - 图1 (opens new window).

Getting Vuex State into Vue Components

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 propertyState - 图2 (opens new window):

  1. // let's create a Counter component
  2. const Counter = {
  3. template: `<div>{{ count }}</div>`,
  4. computed: {
  5. count () {
  6. return store.state.count
  7. }
  8. }
  9. }

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 provides a mechanism to “inject” the store into all child components from the root component with the store option (enabled by Vue.use(Vuex)):

  1. const app = new Vue({
  2. el: '#app',
  3. // provide the store using the "store" option.
  4. // this will inject the store instance to all child components.
  5. store,
  6. components: { Counter },
  7. template: `
  8. <div class="app">
  9. <counter></counter>
  10. </div>
  11. `
  12. })

By providing the store option to the root instance, the store will be injected into all child components of the root and will be available on them as this.$store. Let’s update our Counter implementation:

  1. const Counter = {
  2. template: `<div>{{ count }}</div>`,
  3. computed: {
  4. count () {
  5. return this.$store.state.count
  6. }
  7. }
  8. }

The mapState Helper

Try this lesson on Scrimba

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, saving us some keystrokes:

  1. // in full builds helpers are exposed as Vuex.mapState
  2. import { mapState } from 'vuex'
  3. export default {
  4. // ...
  5. computed: mapState({
  6. // arrow functions can make the code very succinct!
  7. count: state => state.count,
  8. // passing the string value 'count' is same as `state => state.count`
  9. countAlias: 'count',
  10. // to access local state with `this`, a normal function must be used
  11. countPlusLocalState (state) {
  12. return state.count + this.localCount
  13. }
  14. })
  15. }

We can also pass a string array to mapState when the name of a mapped computed property is the same as a state sub tree name.

  1. computed: mapState([
  2. // map this.count to store.state.count
  3. 'count'
  4. ])

Object Spread Operator

Note that mapState returns an object. How do we use it in combination with other local computed properties? Normally, we’d have to use a utility to merge multiple objects into one so that we can pass the final object to computed. However with the object spread operatorState - 图3 (opens new window), we can greatly simplify the syntax:

  1. computed: {
  2. localComputed () { /* ... */ },
  3. // mix this into the outer object with the object spread operator
  4. ...mapState({
  5. // ...
  6. })
  7. }

Components Can Still Have Local State

Using Vuex doesn’t mean you should put all the state in Vuex. Although putting more state into Vuex makes your state mutations more explicit and debuggable, sometimes it could also make the code more verbose and indirect. If a piece of state strictly belongs to a single component, it could be just fine leaving it as local state. You should weigh the trade-offs and make decisions that fit the development needs of your app.