赞
踩
实际上,购物车的实现方式在大体上是相似的,不过小程序有其特有的一套数据层和业务层架构。在此,我将记录并分享之前我们采用的方法,希望对有需求的朋友们能提供一些参考价值。
在最开始的时候,我们会从本地存储中获取购物车的数据。因为我们会频繁地切换不同的页面,而在页面切换的过程中,我们需要实时地重新加载购物车的最新数据。因此,我们将获取数据的方法写在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();
- }
Copy
点击按钮更改购物车的数量:
- 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();
- }
Copy
加载购物车数据的方法:
- data: {
- cart: {},
- address: {},
- totalPrice: 0,
- categoryLength: 0,
- isAllChecked: true
- },
Copy
单个商品被选中时触发:
- 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
- });
- },
Copy
全选和反选触发的事件:
- 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
- })
- },
Copy
点击结算时触发:
- 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();
- },
Copy
纯js代码,可能有一定小程序代码经验的会看得轻松一点。以上便可以实现在对购物车的商品进行加减和全选与反选,以及对商品进行数量合计并计算价格。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。