Reputation: 343
I am wondering what's the syntax for mapGetters when I want to give a custom name to it and use this custom name in my template to access it rather than the getters name.
const store = createStore({
modules: {
prods: productsModule,
cart: cartModule
}
});
My mapGetters with wrong syntax: ** ['products'] is my getters function name.
...mapGetters({
prod: 'prods', ['products']
})
It works if I do it like this, but I want to use mapGetters to do it
products() {
return this.$store.getters['prods/products'];
}
While in my template:
<product-item
v-for="prod in products"
:key="prod.id"
:id="prod.id"
:title="prod.title"
:image="prod.image"
:description="prod.description"
:price="prod.price"
></product-item>
Can't find online for the correct syntax to do this, please let me know if this is possible. Thanks a bunch!
Upvotes: 4
Views: 1508
Reputation: 138646
mapGetters(namespace: string, nameLookup: object)
The first argument is the namespace name, and the second argument is an object lookup, where the key is the custom name to be used in your component, and the value is the original getter name. This is especially useful when you want to map several getters from the same namespace:
// maps this.myCustomProducts to this.$store.getters['prods/products']
mapGetters('prods', { myCustomProducts: 'products' })
Example:
<template>
<div>
<product-item v-for="prod in myCustomProducts" />
<h2>Total: {{ cartTotal }}</h2>
</div>
</template>
<script>
export default {
computed: {
...mapGetters('prods', { myCustomProducts: 'products' }),
...mapGetters('cart', { cartTotal: 'total' }),
}
}
</script>
mapGetters(nameLookup: object)
Alternatively, you could include the namespace name in the lookup value, where the original getter name would be prefixed with the namespace and a slash separator:
mapGetters({
myCustomProducts: 'prods/products',
cartTotal: 'cart/total',
})
Example:
<template>
<div>
<product-item v-for="prod in myCustomProducts" />
<h2>Total: {{ cartTotal }}</h2>
</div>
</template>
<script>
export default {
computed: {
...mapGetters({
myCustomProducts: 'prods/products',
cartTotal: 'cart/total'
}),
}
}
</script>
Upvotes: 4