[vue, javascript] array 속 item들의 총 합계 구하기

2023. 8. 8. 13:26FrontEnd/JavaScript

product list 안의 item들의 총 합계를 구하려고 한다.

vue를 사용하여 작업하였고 methods 안에서 getItems로 배열을 불러온 상태.

computed에서 총합계를 구하려고 함

    data(){
        return {
            items: []
        }
    },
	computed: {
		totalAmount: function () {
			this.itemTotal = this.items.map(function(item) {
				return item.salesAmount * item.itemPrice;
			});
			this.sum = 0;
			this.itemTotal.forEach(n=> {
			  this.sum += n;
			})
			return this.sum;
		}
	},
    methods: {
        getItems() {
          fetch(api)
            .then(res => {
                if (res.ok) {
                    return res.json()
                }
                else
                {
                    if(res.status == 401) {
                        alert('인증이 만료되었습니다');
                        window.location.reload();
                    } else {
                        alert('서버와의 통신 중 오류가 발생했습니다.');
                    }
                }
            })
            .then(res => {
                this.items = res;
            });
        },
    }

getItems 함수에서 불러온 list을 map을 돌려 item 각각의 갯수(salesAmount)와 가격(itemPrice)을 곱하여 item total값을 만들어준 후 forEach를 사용하여 모든 item들의 총합계 금액을 더해주면 끝!