Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use `mapActions` or `mapGetters` with Vuex 4 and Vue 3

Anybody knows how to use mapState or mapGetters with Vue 3 in the setup function ? I know that is possible to use the store with the useStore hook but with this hook We import all the store while with mapState or mapGetters we can specify a module :

// ...

computed: {
   ...mapGetters('myModule', [
      'myStateVariable'
   ]
) 

//...
like image 720
Adri HM Avatar asked Aug 02 '20 13:08

Adri HM


People also ask

Is Vuex compatible with Vue 3?

The functionality of most plugins could be replicated with the Composition API, but Vuex does this better and with a more organized structure. The short answer is: Yes. Vuex is the preferred state management solution for Vue apps, and Vuex 4 is the version compatible with Vue 3.

What is mapActions Vuex?

In Vuex, actions are (usually) asynchronous operations which carry out mutations, as opposed to direct updates to the state. mapActions is just a helper that lets you call those methods from within a Vue component.

What is mapGetters in VueJS?

The mapGetters helper simply maps store getters to local computed properties: import { mapGetters } from 'vuex' export default { // ... computed: { // mix the getters into computed with object spread operator ... mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }


2 Answers

As far as I can tell, they get flattened so you can't use myModule/myStateVariable, but myStateVariable should work.

This could be something that may change as Vuex gets to RC releases, but for now if you try to have the same getter twice, you get this error

enter image description here

like image 86
Daniel Avatar answered Oct 02 '22 17:10

Daniel


Perhaps something like this:

import { computed }  from 'vue';
import { useStore } from 'vuex';

const module = 'myModule';

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

        return {
            // getter
            one: computed(() => store.getters[`${module}/myStateVariable`],

            // state
            two: computed(() => store.state[module].myStateVariable,
        };
    },
};
like image 32
Matt Deacalion Avatar answered Oct 02 '22 16:10

Matt Deacalion