How to access Vuex store in Vue setup() method?
Asked Answered
R

1

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.

Renaerenaissance answered 18/8, 2021 at 18:53 Comment(0)
R
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)
    }
  }
}
Renaerenaissance answered 18/8, 2021 at 18:53 Comment(3)
How to do it in vue 2.7 (with composition API)?Violetavioletta
@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> `Yesseniayester
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.Hemidemisemiquaver

© 2022 - 2024 — McMap. All rights reserved.