2

I've got a computed method that allows me to count a total price of my products and discount value and would like to get the value of: total - discount.

cartTotal() {
    var total = 0;
    var discount = Math.round((0.1 * this.cartTotal) * 100) / 100;
    this.cart.items.forEach(function(item) {
      total += item.quantity * item.product.price;
    });
    total -= discount;
    return total;
}

Doens't work for me and I get that Maximum call stack size exceeded error.

10
  • Are these computed variables? Commented Feb 28, 2018 at 20:47
  • You expect this.discountValue.discount to call your discountValue() method? Commented Feb 28, 2018 at 20:47
  • 1
    discountValue.discount makes no sense (neither does setting discountActive = true then immediately throwing it away). What are you trying to do? Commented Feb 28, 2018 at 20:47
  • 2
    discountValue() seems to assume that cartTotal() returns a price without the discount subtracted from it, but then in cartTotal() you want to subtract the discount from it. There is a logical error here. You must make up your mind: does cartTotal() include the discount or not? Commented Feb 28, 2018 at 20:52
  • I've got some products that have prices and after typing a correct code to give discount to the price of that product. So I calculate the value of the discount and would like it to be 0,1 of my total price: ` var discount = Math.round((0.1 * this.cartTotal) * 100) / 100` - that's correct. Then would like to subtract that value from my main value total. Commented Feb 28, 2018 at 20:54

1 Answer 1

5

You're getting that error because you have two computed properties that reference each others' value. Whenever you do that, you create a cyclical dependency which will generate a "Maximum call stack size exceeded" error.

You really have three values you're dealing with 1) a sum of all values in the cart, 2) a discount amount, and 3) a total value which is the sum minus the discount.

You should have three computed properties:

computed: {
  cartSum() {
    return this.cart.items.reduce((n, i) => n += i.quantity * i.product.price, 0);
  },
  discountValue() {
    return Math.round((0.1 * this.cartSum) * 100) / 100;
  },
  cartTotal() {
    return this.cartSum - this.discountValue;
  },
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it works, that's what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.