Maximum call stack size exceeded - Vue.js

依然范特西╮ 提交于 2021-02-10 18:21:42

问题


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.


回答1:


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;
  },
}


来源:https://stackoverflow.com/questions/49038211/maximum-call-stack-size-exceeded-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!