Home > Software design >  Why use useStore() in vue 3 composition api?
Why use useStore() in vue 3 composition api?

Time:02-03

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

Update: it seems to be easier to mock store in unit tests when useStore() is used.

CodePudding user response:

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

  • Related