Search code examples
javascriptvue.jsvuejs3vuexvue-composition-api

Why use useStore() in vue 3 composition api?


Can you please explain what is the reason to use useStore() function in vue 3 component (composition-api)?

I'm confused, because the direct import of the store is also works, e.g.:

<script setup>
import { store } from '@/store';

const foo = computed(() => store.getters['foo']); // works!
</script>

But a lot of the time I see people are using useStore() instead:

<script setup>
import { useStore } from 'vuex';

const store = useStore();

const foo = computed(() => store.getters['foo']); // also works well
</script>

Why? So far feels just as an extra line of code. I assume I'm missing something.

Thank you


Important update: I learned that useStore() needed if you are doing unit testing and want to mock the store.


Solution

  • It is all about the newest store instance in composition API, as per docs:

    We talk about how to retrieve the store in Vue 2 & Vuex 3 Project. Maybe you already have the answer, it's very easy, just use this.$store. But, We know about Composition API, Inside setup() this won't be a reference to the current active instance Since setup() is called before other component options are resolved.

    documentation