somascope
10/30/2018 - 11:55 PM

Vuex helpers

Vuex has helper functions to give you simpler access to the store's properties. When a component needs to make use of multiple store properties, declaring all these can get repetitive and verbose.

Examples: mapState, mapGetters and mapMutations

<script>
import { mapGetters, mapState, mapMutations } from 'vuex'

export default {
  computed: {
    // mix this into the outer object with the object spread operator
    ...mapState([
      'currentPage'
    ]),
    
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'pageCount'
    ]),
  },
  methods: {
    ...mapMutations([
      'increment', // map `this.increment()` to `this.$store.commit('increment')`

      // `mapMutations` also supports payloads:
      'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
    ])
  }
}
</script>