[Vuejs]-How to calculate total from three components in Vuejs?

1👍

One way to solve it is to have each room emit an event with its price and tack on the room id (or some other unique value)

<tr 
    v-for="roomType in roomTypes"
    :key="roomType.id"
>
    <select-room-details
      v-on:total-price="roomPriceUpdated(roomType.id, $event)"
    />
</tr>

And store that in data with a computed value that sums the prices.

<script>
export default {
  data() {
    return {
      roomPrices: {}
    }
  },
  methods: {
    onRoomPriceUpdated(roomId, price) {
        this.roomPrices[roomId] = price;
    }
  },
  computed: {
    totalPrice() {
        return Object.values(this.roomPrices)
            .reduce((roomPrice, totalPrice) => roomPrice + totalPrice, 0);
    }
  }
}
</script>

The sum should now be available as this.totalPrice within the component.

Leave a comment