小程序购物车 全选、单选、计算总价js

这段代码实现了购物车中的商品选中状态管理,包括单个商品选中、全选功能,以及总价的实时计算。当商品选中状态改变时,会更新选中列表,并根据选中状态计算总价。此外,onLoad和onShow事件用于初始化和刷新页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 购物车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();
        
          },


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值