小程序-商城思路开拓

244 阅读1分钟

引言


小程序商城类写了比较多,想罗列一下写法,因为一直是自己在思考,所以进步比较慢。还请海涵

自己的链接

小程序排坑

购物车

大概思路是通过更新机制去处理各个情况,确保一个函数只做一件事。

  1. 选择商品
const { index,type } = e.currentTarget.dataset;
const goodsList = this.data.goodsList;
goodsList[index].isclick = !goodsList[index].isclick
this.updata(goodsList, type);   

  1. 增加与减少商品数量
add_count(e) {
    const {
      index,
      type
    } = e.currentTarget.dataset;
    const goodsList = this.data.goodsList;
    if (goodsList[index].count <= 0) return
    goodsList[index].count--;
    this.updata(goodsList, type);
  },
  reduce_count(e) {
    const {
      index,
      type
    } = e.currentTarget.dataset;
    const goodsList = this.data.goodsList;
    if (goodsList[index].count === 99) return
    goodsList[index].count++;
    this.updata(goodsList, type);
  },

  1. 全局更新
let total_price = 0;
let isall_status = false; //是否全选
let { isall}=this.data
if (!(list instanceof Array)) {
  //小程序原生点击事件第一项为event,默认点击替换,vue则不会
  list = this.data.goodsList
  type = true
}
list.forEach(item => {
  if (type) {
    !isall ? item.isclick = true : item.isclick = false
  }
  if (item.isclick) {
    total_price += parseInt(item.price * item.count)
  }
})
isall_status = list.filter(item => item.isclick).length;
isall_status === list.length ? isall = true : isall = false
this.setData({
  goodsList: list,
  total_price,
  isall
})

4.删除商品

let {
  goodsList,
} = this.data;
let delete_list = goodsList.filter(item => item.isclick);
let status_length = delete_list.length;
let Model_content = status_length === goodsList.length ? '是否删除全部商品' : '是否删除商品'
Model('温馨提示', Model_content).then(res => {
  goodsList.forEach((item, index, arr) => {
    if (item.isclick) {
      goodsList.splice(index, status_length)
    }
  })
  Toast('删除成功')
  this.setData({
    goodsList,
    total_price: 0
  })
})