// 购物车js
data: {
//购物车列表
Goods: [],
index: '',
isAllselected: false,
totalPrice: 0,
rid: '',
selectedList: [], //选中列表
goodsCarts: [] //去结算的列表
},
// 选中当前商品radio
radioChange(e) {
var that = this;
let index = e.currentTarget.dataset.index;
let rid = e.currentTarget.dataset.rid;
var Goods = this.data.Goods.find(item => {
return item.id === rid
})
let i = that.data.selectedList.indexOf(that.data.Goods[index].id);
if (i > -1) {
that.data.selectedList.splice(i, 1)
} else {
that.data.selectedList.push(that.data.Goods[index].id);
}
Goods.checked = !Goods.checked;
let isAllselected = that.data.Goods.every(r => r.checked);
that.setData({
Goods: that.data.Goods,
isAllselected,
index: index,
selectedList: that.data.selectedList,
rid: rid
})
that.total()
},
//全选
radioItems() {
let newgoods = this.data.Goods;
let ridList = [];
let isAllselected = this.data.isAllselected;
newgoods.forEach(element => {
if (isAllselected == false) {
element.checked = true;
ridList.push(element.id);
}
if (isAllselected == true) element.checked = false;
});
isAllselected = !isAllselected;
this.setData({
selectedList: ridList,
Goods: newgoods,
isAllselected: isAllselected
})
this.total()
},
// 计算价格
total() {
let totalPrice = 0;
let Goods = this.data.Goods; // 获取购物车列表
for (let i = 0; i < Goods.length; i++) { // 循环列表得到每个数据
if (Goods[i].checked) { // 判断选中才会计算价格
totalPrice += Goods[i].amount * Goods[i].price; // 所有价格加起来
} else {
totalPrice == 0
}
}
this.setData({ // 最后赋值到data中渲染到页面
Goods: Goods,
totalPrice: totalPrice.toFixed(2)
});
},
onLoad() {
this.setData({
totalPrice: 0
})
},
onShow() {
this.GoodsList();
this.total();
this.onLoad();
},
小程序购物车 全选、单选、计算总价js
最新推荐文章于 2023-10-24 22:58:27 发布