9

How do I access the Vuex store in Vue when using the setup() method?

I don't have access to the regular this.$store variable anymore.

1 Answer 1

15

According to the composition API documentation you have to use the following syntax:

import { computed } from 'vue' // If not already imported
import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()

    return {
      // access a state in computed function
      count: computed(() => store.state.count),

      // access a getter in computed function
      double: computed(() => store.getters.double)
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

How to do it in vue 2.7 (with composition API)?
@Md.A.Apu This should do the trick ` <script setup> ... import store and other deps const store = useStore(); const count = computed(() => store.state.count); etc... </script> `
Note that you may need to add import { computed } from 'vue' just below the import of { useStore }, otherwise it throws an error on the use of the computed keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.