微信小程序开发之自定义购物车

2018-06-07  本文已影响0人  Just丶Go
购物车展示.gif

不啰嗦直接上代码
代码里都有详细注释

另在wxml中已经使用<template></template>将每个item进行封装

.js 代码


var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopping_list: [],  // 购物车列表
    is_edit: false, // 是否编辑过, 若编辑过则页面消失时会提交接口
    is_all_selected: false, // 购物车是否全部被选中
    selected_count: 0, // 被选中的数量
    total_money: 0,
  },
  /**
   * 购买操作
   */
  buyAction: function(e) {
    var that = this
    console.log("结算!")
    // 检测是否有勾选商品
    if (!(this.data.selected_count >0)) {
      wx.showToast({
        title: '您还没有选择商品哦',
        icon: "none",
        complete: function () {

        }
      })
      return
    }
    var selected_list = []
    for (var i = 0; i < this.data.shopping_list.length; i++) {
      if (this.data.shopping_list[i].is_selected) {
        selected_list.push(this.data.shopping_list[i])
      }
    }
    // 跳至结算页
    wx.navigateTo({
      url: 'order_pay/order_pay?selected_list=' + selected_list,
    })

  },

  /**
   * 选择按钮 是否选中事件
   */
  selectionAction: function(e) {
    var index = e.currentTarget.dataset.index
    var cur_cell = this.data.shopping_list[index]
    cur_cell.is_selected = !cur_cell.is_selected
    this.setData({
      shopping_list: this.data.shopping_list,
      is_edit: true // 编辑过
    })
    // 判断是否全部选中
    this.isAllSelected()
    console.log(index)
  },
  /** 
   * 全选按钮
   */
  selectedAllAction: function (e) {
    // 设置按钮状态
    this.setData({
      is_all_selected: !this.data.is_all_selected
    })
    if (this.data.is_all_selected) { // 若全选
      this.setIs_selected(this.data.shopping_list, true)
      // 
      this.isAllSelected()
    } else { // 若全部取消
      this.setIs_selected(this.data.shopping_list, false)
      // 
      this.isAllSelected()
    }
  },
  // 设置模型中的is_selected字段
  setIs_selected: function (list, isSelected) {
    for (var i = 0; i < list.length; i++) {
      var item = list[i]
      item.is_selected = isSelected
    }
    this.setData({
      shopping_list: list
    })
  },
  /**
   * 设置属性值
   * 是否全部选中、      选中的数量、      选中商品的总价
   * is_all_selected、selected_count、total_money
   */
  isAllSelected: function() {
    // 循环遍历查看是否全部选中
    var count = 0
    var total_pay = 0
    for (var i = 0; i < this.data.shopping_list.length; i++) {
      // 若选中, 则增加
      if (this.data.shopping_list[i].is_selected) {
        count++
        var price = this.data.shopping_list[i].count * this.data.shopping_list[i].salesPrice
        // 设置售价
        total_pay += price 
      }
    }

    //  赋值总花费、选中数量
    this.setData({
      selected_count: count,
      total_money: total_pay
    })
    // 赋值成员变量selected_count 
    // 若选中的数量count == 购物车列表长度, 则全选;反之, 不全选
    if (count == this.data.shopping_list.length) {
      this.setData({
        is_all_selected: true
      })
    } else {
      this.setData({
        is_all_selected: false
      })
    }
    
  },
  /**
   * 数量+++++
   */
  addAction: function(e) {
    var index = e.currentTarget.dataset.index
    var cur_cell = this.data.shopping_list[index]
    cur_cell.count++
    this.setData({
      shopping_list: this.data.shopping_list,
      is_edit: true // 编辑过
    })

    // 
    this.isAllSelected()
    /**
     * 提交修改后的数据
     * 将修改后的数据提交时机放到页面离开时```
     * /api/XingluShoppingCar/EditAmount
     * 
     */
    console.log("增加")
    console.log(cur_cell)

  },
  /**
   * 数量-----
   */
  subAction: function(e) {
    var index = e.currentTarget.dataset.index
    var cur_cell = this.data.shopping_list[index]
    cur_cell.count > 1 ? cur_cell.count-- : cur_cell.count
    this.setData({
      shopping_list: this.data.shopping_list
    })
    // 
    this.isAllSelected()

    console.log("减少")
    console.log(cur_cell)
  },
  /**
   * 删除购物车中某件商品
   */
  deleteAction: function(e) {
    var that = this
    wx.showModal({
      title: '确定要删除该商品吗',
      confirmColor: "#d32433",
      success: function(res) {
        if (res.confirm) { // 确定
          // 删除该组商品
          var index = e.currentTarget.dataset.index
          that.data.shopping_list.splice(index, 1)
          that.setData({
            shopping_list: that.data.shopping_list
          })
        } else if (res.cancel) { // 取消

        }
        console.log("确定?")
        console.log(res)
      },
      fail: function(err) {
        console.log("失败")
        console.log(err)
      },
      // 完成后, 判断商品是否全部选中, 以便及时更改全选按钮状态
      complete: function() {
        that.isAllSelected()
      }
    })
    

  },
  /**
   * 获取购物车数据
   */
  getShoppingData: function() {
    var that = this;
    wx.request({
      url: app.globalData.service_host + '获取购物车数据',
      method: "POST",
      data: { tokenName: "CA17E6EE-BF7C-48CF-83B8-EEC11EC7F0C2" },
      success: function (res) {
        console.log("购物车列表\n")
        console.log(res)
        // 为每组数据添加is_selected 字段
        if (res.data.resultData) {
          that.setIs_selected(res.data.resultData, false)
        }


      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getShoppingData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

    // 获取购物车列表每件商品的id及数量count
    var list = []
    if (this.data.shopping_list) {
      for (var i = 0; i < this.data.shopping_list.length; i++) {
        list.push({ id: this.data.shopping_list[i].id, amount: this.data.shopping_list[i].count })
      }
    }
    
    if (!this.data.is_edit) return
    // 若编辑过,则将状态复原为默认值 false
    // 复原属性值
    this.setData({
      is_edit: false,
      is_all_selected: false,
      total_money: 0
    })
    console.log(list)
    /**
     * 页面隐藏时,提交修改后的购物车数据
     * /api/XingluShoppingCar/EditAmount
     */
    wx.request({
      url: app.globalData.service_host+ 'url:提交修改后的购物车数据',
      method: "POST",
      data: { tokenName: "CA17E6EE-BF7C-48CF-83B8-EEC11EC7F0C2", list: list},
      success: function(res) {
        console.log(res)
      },
      fail: function(err) {
        console.log("购物车修改提交失败!")
        console.log(err)
      },
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

.wxml


<!--单品信息 item  -->
<template name="cell">
  <view class='item'>
    <!--选择框  -->
    <image class='selection-icon'
     src='{{is_selected?"../../images/sel_sel.png":"../../images/sel_nor.png"}}' bindtap='selectionAction' data-index='{{index}}'>
    </image>
    <!--商品图  {{productImage}}-->
    <image class='product-icon'      src='{{productImage}}'></image>
    <!--商品描述、数量选择  -->
    <view class='item-desc'>
      <!--商品名 {{productName}}  -->
      <text class='name' style='font-size: 13px;'>{{productName}}</text>
      <view class='color-size'>
        <text style='font-size: 12px;'>颜色: </text>
        <!--颜色 {{colourUrl}}  -->
        <image src='{{colourUrl}}' style='width: 24rpx; height: 24rpx;'></image>
        <text style='font-size: 12px;'>;</text>
        <!--尺码 {{size}}  -->
        <text style='font-size: 10px;'>尺码: {{size}};</text>
      </view>
      <view class='counter'>
        <view class='counter-item' bindtap='subAction' data-index='{{index}}'>-</view>
        <view class='counter-line'></view>
        <!--数量 {{count}}  -->
        <text class='counter-item'>{{count}}</text>
        <view class='counter-line'></view>
        <view class='counter-item' bindtap='addAction' data-index='{{index}}'>+</view>
      </view>
    </view>
    <!--商品售价、删除  -->
    <view class='price-delete'>
      <!--售价 {{salesPrice}}  -->
      <text class='sale-price'>¥{{salesPrice}}</text>
      <!--标价 {{tagPrice}}  -->
      <text class='tag-price'>¥{{tagPrice}}</text>
      <image class='delete-icon' src='../../images/delete.jpeg' bindtap='deleteAction' data-index='{{index}}'></image>
    </view>
  </view>
</template>

<view class='container'>
<!--传入购物车列表数据  -->
  <block wx:for="{{shopping_list}}" wx:key="shopping_list">
    <template is="cell" data="{{...item,index}}"></template>
  </block>
  <view class='bottom-line'></view>
</view>

<!--底部结算栏  -->
<view class='bottom-line-view'></view>
<view class='bottom-view'>
  <image class='all-selection-icon' src='{{is_all_selected?"../../images/sel_sel.png":"../../images/sel_nor.png"}}' bindtap='selectedAllAction'></image>
  <text class='total-count'>全选 ({{selected_count}})</text>
  <text class='total-money'>¥{{total_money}}</text>
  <button class='buy' bindtap='buyAction' >结 算</button>
</view>

.wxss


/*  cell  */
.item {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 240rpx;
  margin-top: 20rpx;
  background-color: #fff; 
}
/*选择框  */
.selection-icon {
  margin-left: 20rpx;
  width: 36rpx;
  height: 36rpx;
}
/*产品图  */
.product-icon{
  width: 150rpx; 
  height: 180rpx;
}
/*商品描述  */
.item-desc {
  position: relative;
  display: flex;
  flex-direction: column;
  align-self: flex-start;
  margin-top: 30rpx;
  width: 300rpx;
  height: 180rpx;
}
/*颜色&尺码  */
.color-size {
  position: absolute;
  bottom: 50rpx;
  width: 100%;
  height: 50rpx;
}
/*数量选择器  */
.counter {
  position: absolute;
  bottom: 0;
  display: flex;
  flex-direction: row;
  border: solid 1px #000; 
  width: 182rpx; 
  border-radius: 6rpx;
  margin-top: 20rpx;
}
/*加减&数量  */
.counter-item {
  font-size: 14px; 
  width: 60rpx; 
  height: 40rpx; 
  text-align: center;
}
/*竖线  */
.counter-line {
  height: 40rpx; 
  width: 1px; 
  background-color: #000;
}
/*价格&删除  */
.price-delete {
  position: relative;
  display: flex;
  flex-direction: column;
  align-self: flex-start;
  align-items: flex-end;
  width: 150rpx;
  height: 180rpx;
  margin-top: 30rpx;
  margin-right: 20rpx;
}
/*售价  */
.sale-price {
  font-size: 14px;
  font-weight: bold; 
}
/*标价  */
.tag-price {
  font-size: 12px;
  color: #d32433;
  text-decoration: line-through;
}
/*删除  */
.delete-icon {
  position: absolute;
  bottom: 0;
  width: 64rpx; 
  height: 64rpx;
}
/*  cell  */

page {
  background-color: #f5f5f5;
}
.bottom-line {
  width: 100%;
  height: 120rpx;
}

.bottom-line-view {
  position: fixed;
  left: 0; bottom: 90rpx;
  width: 100%;
  height: 1px;
  background-color: #f1f1f1;
}
.bottom-view {
  position: fixed;
  left: 0; bottom: 0;
  width: 100%;
  height: 90rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff;
}
.all-selection-icon {
  width: 36rpx;
  height: 36rpx;
  margin-left: 20rpx;
}
.total-count {
  margin-left: 30rpx;
  font-size: 14px;
  width: 130rpx;
   color: #646363; 
}

.buy {
  margin-right: 20rpx;
  width: 120rpx;
  height: 60rpx;
  font-size: 13px;
  padding: 0;
  line-height: 60rpx;
  background-color: #d32433;
  color: #fff;
}
.button-hover {
  opacity: 0.8;
}
.total-money {
  width: 160rpx;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 14px;
  margin-left: 224rpx;
  text-align: right;
  font-weight: bold;
}
上一篇下一篇

猜你喜欢

热点阅读