Composition API

To access the store within the setup hook, you can call the useStore function. This is the equivalent of retrieving this.$store within a component using the Option API.

  1. import { useStore } from 'vuex'
  2. export default {
  3. setup () {
  4. const store = useStore()
  5. }
  6. }

Accessing State and Getters

In order to access state and getters, you will want to create computed references to retain reactivity. This is the equivalent of creating computed properties using the Option API.

  1. import { computed } from 'vue'
  2. import { useStore } from 'vuex'
  3. export default {
  4. setup () {
  5. const store = useStore()
  6. return {
  7. // access a state in computed function
  8. count: computed(() => store.state.count),
  9. // access a getter in computed function
  10. double: computed(() => store.getters.double)
  11. }
  12. }
  13. }

Accessing Mutations and Actions

When accessing mutations and actions, you can simply provide the commit and dispatch function inside the setup hook.

  1. import { useStore } from 'vuex'
  2. export default {
  3. setup () {
  4. const store = useStore()
  5. return {
  6. // access a mutation
  7. increment: () => store.commit('increment'),
  8. // access an action
  9. asyncIncrement: () => store.dispatch('asyncIncrement')
  10. }
  11. }
  12. }

Examples

Check out the Composition API example to see example applications utilising Vuex and Vue’s Composition API.