Search code examples
javascriptvue.jsvuexvuejs3

Vue 3 mapGetters problem mutliple getters not working


My getters

const state = {
    pakets: [
        { id: 1, paketname: "Simple", price: "5" },
        { id: 2, paketname: "Silver", price: "10" },
        { id: 3, paketname: "Gold", price: "15" },
        { id: 4, paketname: "Platin", price: "25" },
    ],
    basket:[],
}

 const getters = {
   getBaskets(state){
     return state.basket
   },
   getTotal(state){
     let total = 0;
     state.basket.forEach(x=> this.total += 1 * x.price)
     return total;
   }
 }

My component

<script>
import { mapGetters } from "vuex";
export default {
  computed:{
    ...mapGetters([
        'getBaskets',
        'getTotal'
    ]),
  },
};
</script>

Hi everyone I wrote a basket in my own project, but I want to calculate the total in this base. The mapgetter only works when it receives one getters, but it does not work when there are 2 or more, I can't find out what could be the reason. Thanks


Solution

  • Try like this:

    const getters = {
      getBaskets: (state) => state.basket,
      getTotal: (state) => state.basket.reduce((acc, x) => acc += Number(x.price), 0)
    }