微信小程序实现购物车代码实例详解
人气:2其实购物车都是类似的实现方法,只不过小程序是有他的数据层和业务层,在这里把之前的做法记录一下,分享出来也希望能给需要的小伙伴带来参考价值在最开始的时候先从本地存储中获取购物车数据,因为我们会切换页面 在页面切换的过程中需要实时重新加载购物车的数据,所以我们把获取的方法写在onShow中,而不是onLoad中:
onShow: function () { const cart = wx.getStorageSync("cart"); let address = wx.getStorageSync("address") ; console.log(address); this.setData({ address, cart }) this.loadCarts(); this.countAll(); }
点击按钮更改购物车的数量:
handleNumEdit(e) { const { operator, goodsid } = e.target.dataset; let { cart } = this.data; cart[goodsid].count += (+operator); if (cart[goodsid].count < 1) { cart[goodsid].count = 1; wx.showModal({ title: '提示', content: '您确定要删除吗', showCancel: true, cancelText: '取消', cancelColor: '#000000', confirmText: '确定', confirmColor: '#3CC51F', success: (result) => { if (result.confirm) { delete cart[goodsid]; this.loadCarts(); this.countAll(); } else { } } }); } else if (cart[goodsid].count > cart[goodsid].goods_number) { cart[goodsid].count = cart[goodsid].goods_number; wx.showToast({ title: '没有库存了', icon: 'none', duration: 1500, mask: true }); } this.loadCarts(); this.countAll(); }
加载购物车数据的方法:
data: { cart: {}, address: {}, totalPrice: 0, categoryLength: 0, isAllChecked: true },
单个商品被选中时触发:
loadCarts() { let { cart } = this.data; let isAllChecked = true; for (const key in cart) { if (cart.hasOwnProperty(key)) { const element = cart[key]; if (!element.isChecked) { isAllChecked = false; break; } } } this.setData({ cart, isAllChecked }); },
全选和反选触发的事件:
handleItemChecked(e) { let { goodsid } = e.target.dataset; let { cart } = this.data; let { isChecked } = cart[goodsid]; cart[goodsid].isChecked = !isChecked; let checkedLength = 0; for (const key in cart) { if (cart.hasOwnProperty(key)) { if (cart[key].isChecked) { checkedLength++; } } } const isAllChecked = checkedLength == Object.keys(cart).length; this.countAll(); this.setData({ isAllChecked }) },
点击结算时触发:
handleItemAllChecked() { let { isAllChecked } = this.data; let { cart } = this.data; isAllChecked = !isAllChecked; for (const key in cart) { if (cart.hasOwnProperty(key)) { cart[key].isChecked = isAllChecked; } } this.setData({ isAllChecked, cart }) this.countAll(); },
纯js代码,可能有一定小程序代码经验的会看得轻松一点。以上便可以实现在对购物车的商品进行加减和全选与反选,以及对商品进行数量合计并计算价格。
您可能感兴趣的文章:
加载全部内容