Vue.js/Vuex

[Vuex] mapState

brightlightkim 2022. 5. 13. 08:12

Where there is multiple state inside our component state, we use them.

 

export default {
    data() {
        return {
        }
    },
    computed: mapState({
      students: state => state.students
    }),
  async created() {
  }
};

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:

// in full builds helpers are exposed as Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // arrow functions can make the code very succinct!
    count: state => state.count,

    // passing the string value 'count' is same as `state => state.count`
    countAlias: 'count',

    // to access local state with `this`, a normal function must be used
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

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.

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

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 operator, we can greatly simplify the syntax:

computed: {
  localComputed () { /* ... */ },
  // mix this into the outer object with the object spread operator
  ...mapState({
    // ...
  })
}

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.

'Vue.js > Vuex' 카테고리의 다른 글

[Vuex] dispatch action from another module vuex  (0) 2022.05.20
[Vuex] Modules  (0) 2022.05.13
[Vuex] Actions  (0) 2022.05.13
[Vuex] Mutations  (0) 2022.05.13
[Vuex] Getters  (0) 2022.05.13