totalPrice:function (){ var totalPrice = 0; this.list.forEach(function(item, index){ if(item.isSelect){ totalPrice += item.count * item.uniPrice; } }); return totalPrice; } }
时间: 2024-02-10 19:21:40 浏览: 26
这段代码中,定义了一个方法totalPrice,用于计算选中商品的总价。在方法中,首先定义了一个变量totalPrice,并将其初始化为0。然后使用forEach方法遍历商品列表(this.list),对于每个选中的商品,将其数量(item.count)乘以单价(item.uniPrice),并加到totalPrice中。最后,返回计算好的总价totalPrice。
相关问题
methods:{ getAllTotal(){ let total = 0, num = 0; this.cart.forEach((elm,index) => { total = total + elm.count * elm.price num += elm.count }) this.getTotal.totalPrice = total this.getTotal.totalNum = num } },
根据你提供的代码,问题应该出现在this.cart上,因为this.cart是undefined,而导致了运行时错误。
解决这个问题的方法是,在Vue组件的data选项中定义一个cart数组,并在created生命周期钩子函数中初始化这个数组。例如:
```
export default {
data() {
return {
cart: [] // 定义cart数组
}
},
created() {
// 在created钩子函数中初始化cart数组
this.cart = [
{ id: 1, name: '商品1', price: 10, count: 1 },
{ id: 2, name: '商品2', price: 20, count: 2 },
{ id: 3, name: '商品3', price: 30, count: 3 }
];
this.getAllTotal(); // 初始化完cart数组后,调用计算总价和总数量的方法
},
methods: {
getAllTotal() {
let total = 0, num = 0;
this.cart.forEach((elm,index) => {
total = total + elm.count * elm.price
num += elm.count
})
this.getTotal.totalPrice = total
this.getTotal.totalNum = num
}
}
}
```
在这个例子中,我们在data选项中定义了一个cart数组,并在created生命周期钩子函数中初始化了这个数组。然后,我们调用getAllTotal()方法来计算总价和总数量。这样就可以避免出现undefined的错误了。
删除购物车单项deleteOne: function (e) { var id = e.currentTarget.dataset.id; var index = e.currentTarget.dataset.index; var arr = wx.getStorageSync('cart') for (var i in this.data.foodList) { if (this.data.foodList[i].id == id) { this.data.foodList[i].quantity = 0; } } arr.splice(index, 1); if (arr.length <= 0) { this.setData({ foodList: this.data.foodList, cartList: [], cartFlag: false, totalNum: 0, totalPrice: 0, }) this.cascadeDismiss() } try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } this.setData({ cartList: arr, foodList: this.data.foodList }) this.getTotalPrice() },
这段代码是用来删除购物车中的单个商品项的。首先,它从当前点击的item中获取商品id和索引位置。然后,它从本地缓存中获取购物车商品列表,遍历所有的食品列表,如果商品id与当前点击的id匹配,那么就将该商品的数量设置为0,表示该商品已从购物车中移除。接着,它从购物车商品列表中删除当前点击的商品项,并更新本地缓存中的购物车商品列表。如果购物车商品列表为空,那么就清空购物车,并将购物车状态标记为关闭状态,并调用cascadeDismiss()方法隐藏购物车界面。最后,它更新购物车商品列表和食品列表,并重新计算购物车中商品的总价。