javascript - Dinero Multiply() 不是 cart.totalPrice 中的函数错误
问题描述
我第一次使用 Dinerojs。我在纯 js 文件的购物车中使用它。我在这里包含了我认为相关的部分代码,但如果您需要我发布更多代码,我将附加我的问题。
我的购物车代码很简单——它是一家精巧的商店:
let cartStore = writable({
items: [],
totalPrice: 0,
totalItems : 0
})
我使用以下代码将商品添加到购物车:
cartStore.update(cartStore => {
cartStore.items.push({
product: product,
totalPrice: product.price,
quantity: 1
})
为了计算项目 totalPrice 我试图将 item.totalPrice 乘以数量:
updatedCartStore.items.forEach(item => {
item.totalPrice = item.product.price * item.quantity;
});
现在这段代码在我将 Dinerojs 添加到我的 package.json 并尝试使用 DineroJS 之前有效。当我尝试使用 Dinero 对象时,我遇到了一些我将在稍后解释的问题。
我将 totalPrice 更改为:
let cartStore = writable({
items: [],
totalPrice: Dinero({amount : 0, currency : "USD"}), // >>>>changed this to include Dinero
totalItems : 0
})
当我尝试将 item.product.price 与 item.quantity 相乘时...出现错误,我需要提供一个整数,console.log 将 totalPrice 显示为 NAN。这是我的代码:
updatedCartStore.items.forEach(item => {
item.totalPrice = Dinero({ amount : item.product.price}).multiply(item.quantity);
});
我还尝试了以下方法,这给了我错误“乘法不是函数”:
updatedCartStore.items.forEach(item => {
item.totalPrice = item.product.price.multiply(item.quantity);
});
所以,我的问题是如何使用 Dinero().multiply() 计算 item.totalPrice ?我需要将 item.product.price 乘以 item.quantity 但使用 Dinero.JS。实现这一目标的正确方法是什么?
更新 1:Mybe 我在前面错误地添加了 Dinero:我的前面是这样的:
<ProductCard name ="dinerojs" description="to test using dinerojs" price ={Dinero({amount :40 , currency:"USD" }).toFormat()} options="false" />
Mybe toFormat() 导致数字转换为其他数字?
解决方案
Dinero 要求“金额”为整数值。它以“美分”而不是“美元”跟踪货币交易(他们称之为“次要货币”,因为它支持多种货币)
根据货币的不同,您可能需要采取不同的行动,但默认的小数位数为 2,因此只要您不更改它,您只需转换item.product.price
为整数:
updatedCartStore.items.forEach(item => {
item.totalPrice = Dinero({ amount : item.product.price * 100}).multiply(item.quantity);
});
请记住,如果您切换到日元或秘鲁比索或其他东西,您可能需要调整一些东西。