【问题标题】:Maximum call stack size exceeded - Vue.js超出最大调用堆栈大小 - Vue.js
【发布时间】:2018-08-08 20:14:44
【问题描述】:

我有一个计算方法,可以让我计算我的产品的总价格和折扣值,并希望得到以下值: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;
}

对我不起作用,我收到 Maximum call stack size exceeded 错误。

【问题讨论】:

  • 这些是计算变量吗?
  • 您希望this.discountValue.discount 调用您的discountValue() 方法?
  • discountValue.discount 没有任何意义(设置discountActive = true 也没有,然后立即将其丢弃)。你想做什么?
  • discountValue() 似乎假设cartTotal() 返回的价格没有减去折扣,但是在cartTotal() 中,您想从中减去折扣。这里有一个逻辑错误。你必须下定决心:cartTotal() 是否包含折扣?
  • 我有一些有价格的产品,在输入正确的代码后,该产品的价格可以打折。所以我计算了折扣的价值,并希望它是我总价的 0,1:` var discount = Math.round((0.1 * this.cartTotal) * 100) / 100` - 这是正确的。然后想从我的主要值total中减去那个值。

标签: javascript vue.js


【解决方案1】:

您收到该错误是因为您有两个计算属性引用彼此的值。每当你这样做时,你都会创建一个循环依赖,这将产生一个“超出最大调用堆栈大小”的错误。

您确实要处理三个值:1) 购物车中所有值的总和,2) 折扣金额,以及 3) 总价值,即总和减去折扣。

你应该有三个计算属性:

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

【讨论】:

  • 非常感谢,它有效,这就是我想要的。
猜你喜欢
  • 2019-02-01
  • 2021-09-21
  • 1970-01-01
  • 2015-10-24
  • 2015-12-29
  • 2017-12-27
  • 2020-12-06
  • 2018-02-06
  • 2020-06-28
相关资源
最近更新 更多