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'
]
)
//...
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.
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.
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', // ... ]) } }
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
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,
};
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With