这段代码修改一个商品数量时其他商品数量也会变化,请进行修改const app = getApp() let tableNum = null Page({ data: { cartList: [], totalPrice: 0, // 总价,初始为0 totalNum: 0, //总数,初始为0 }, onShow() { tableNum = wx.getStorageSync("tableNum") let cartList = wx.getStorageSync('cart') || []; this.setData({ cartList }) this.getTotalPrice(); }, // 获取购物车总价、总数 getTotalPrice() { var cartList = this.data.cartList; // 获取购物车列表 var totalP = 0; var totalN = 0 for (var i in cartList) { // 循环列表得到每个数据 totalP += cartList[i].quantity * cartList[i].price; // 所有价格加起来 totalN += cartList[i].quantity } this.setData({ // 最后赋值到data中渲染到页面 cartList: cartList, totalNum: totalN, totalPrice: totalP.toFixed(2) }); }, // 购物车增加数量 addCount(e) { let item = e.currentTarget.dataset.item; let arr = wx.getStorageSync('cart') || []; let f = false; if (arr.length > 0) { for (let j in arr) { // 遍历购物车找到被点击的商品,数量加1 if (arr[j]._id == item._id) { arr[j].quantity += 1; f = true; try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } break; } } if (!f) { arr.push(item); } } else { arr.push(item); } try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } this.setData({ cartList: arr, }, success => { this.getTotalPrice(); }) }, //购物车减少数量 minusCount(e) { let item = e.currentTarget.dataset.item; let cartList = wx.getStorageSync('cart') || [];
时间: 2023-12-06 12:40:07 浏览: 97
修改后的代码如下:
const app = getApp()
let tableNum = null
Page({
data: {
cartList: [],
totalPrice: 0,
totalNum: 0,
},
onShow() {
tableNum = wx.getStorageSync("tableNum")
let cartList = wx.getStorageSync('cart') || [];
this.setData({
cartList
})
this.getTotalPrice();
},
// 获取购物车总价、总数
getTotalPrice() {
var cartList = this.data.cartList;
var totalP = 0;
var totalN = 0
for (var i in cartList) {
totalP += cartList[i].quantity * cartList[i].price;
totalN += cartList[i].quantity
}
this.setData({
totalNum: totalN,
totalPrice: totalP.toFixed(2)
});
},
// 购物车增加数量
addCount(e) {
let item = e.currentTarget.dataset.item;
let arr = wx.getStorageSync('cart') || [];
let f = false;
if (arr.length > 0) {
for (let j in arr) {
if (arr[j]._id == item._id) {
arr[j].quantity += 1;
f = true;
break;
}
}
if (!f) {
arr.push(item);
}
} else {
arr.push(item);
}
try {
wx.setStorageSync('cart', arr)
} catch (e) {
console.log(e)
}
this.setData({
cartList: arr,
})
this.getTotalPrice();
},
//购物车减少数量
minusCount(e) {
let item = e.currentTarget.dataset.item;
let cartList = wx.getStorageSync('cart') || [];
for (let j in cartList) {
if (cartList[j]._id == item._id) {
if (cartList[j].quantity > 1) {
cartList[j].quantity -= 1;
} else {
cartList.splice(j, 1);
}
break;
}
}
try {
wx.setStorageSync('cart', cartList)
} catch (e) {
console.log(e)
}
this.setData({
cartList,
})
this.getTotalPrice();
},
})
阅读全文