Understanding State and Getters in Nuxt.js: Getters won't working
Using factory function for a state
is a nuxt.js feature. It is used in the SSR mode to create a new state for each client. But for getters
it doesn't make sense, because these are pure functions of the state. getters
should be a plain object:
export const getters = {
getName: (state) => {
return state.mistica.name
}
}
After this change getters should work.
Then you can use the this.$store.getters['products/getName']
in your components.
You can't use this.$store.getters.products.getName
, as this is the incorrect syntax.
But to get simpler and more clean code, you can use the mapGetters
helper from the vuex
:
import { mapGetters } from "vuex";
...
computed: {
...mapGetters("products", [
"getName",
// Here you can import other getters from the products.js
])
}
Couple of things. In your "store" folder you might need an index.js for nuxt to set a root module. This is the only module you can use nuxtServerInit
in also and that can be very handy.
In your products.js you are part of the way there. Your state should be exported as a function but actions, mutations and getters are just objects. So change your getters to this:
export const getters = {
getName: state => {
return state.mistica.name
}
}
Then your second computed should get the getter. I usually prefer to use "mapGetters" which you can implement in a page/component like this:
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
getName: 'products/getName'
})
}
</script>
Then you can use getName in your template with {{ getName }}
or in your script with this.getName
.