微信小程序实战 购物车功能

2022-12-02,,,,

代码地址如下:
http://www.demodashi.com/demo/12400.html

一、准备工作

软件环境:微信开发者工具

官方下载地址:https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html

基本需求

显示图书基本信息:名称、作者、描述、价格、数量。
点击复选框进行toggle操作。当前选中,则变成未选中;当前未选中,则变成选中。
图书数量的加减操作。
根据选中商品进行价格汇总。
全选/全不选。

目录结构

二、程序实现步骤

复选框进行toggle操作。当前选中,则变成未选择;当前未选中,则变成选中。购物车商品全部选中,全选按钮为选中状态。购物车商品全部未选中,全选按钮为未选中状态。

  /**
* 用户选择购物车商品
*/
checkboxChange: function (e) {
console.log('checkbox发生change事件,携带value值为:', e.detail.value);
var checkboxItems = this.data.goodList;
var values = e.detail.value;
for (var i = 0; i < checkboxItems.length; ++i) {
checkboxItems[i].checked = false;
for (var j = 0; j < values.length; ++j) {
if (checkboxItems[i].isbn == values[j]) {
checkboxItems[i].checked = true;
break;
}
}
} var checkAll = false;
if (checkboxItems.length == values.length) {
checkAll = true;
} this.setData({
'goodList': checkboxItems,
'checkAll': checkAll
});
this.calculateTotal();
},

商品的加减操作。当前数量大于1,可以进行加减操作;当前数量为1时,只能进行加操作。

  /**
* 用户点击商品减1
*/
subtracttap: function (e) {
var index = e.target.dataset.index;
var goodList = this.data.goodList;
var count = goodList[index].count;
if (count <= 1) {
return;
} else {
goodList[index].count--;
this.setData({
'goodList': goodList
});
this.calculateTotal();
}
}, /**
* 用户点击商品加1
*/
addtap: function (e) {
var index = e.target.dataset.index;
var goodList = this.data.goodList;
var count = goodList[index].count;
goodList[index].count++;
this.setData({
'goodList': goodList
});
this.calculateTotal();
},

用户点击全选/全不选,遍历购物车所有商品设置当前选中状态。

  /**
* 用户点击全选
*/
selectalltap: function (e) {
console.log('用户点击全选,携带value值为:', e.detail.value);
var value = e.detail.value;
var checkAll = false;
if (value && value[0]) {
checkAll = true;
} var goodList = this.data.goodList;
for (var i = 0; i < goodList.length; i++) {
var good = goodList[i];
good['checked'] = checkAll;
} this.setData({
'checkAll': checkAll,
'goodList': goodList
});
this.calculateTotal();
}

选中商品数量发生改变时,进行商品总数量和总价格的计算。

  /**
* 计算商品总数
*/
calculateTotal: function () {
var goodList = this.data.goodList;
var totalCount = 0;
var totalPrice = 0;
for (var i = 0; i < goodList.length; i++) {
var good = goodList[i];
if (good.checked) {
totalCount += good.count;
totalPrice += good.count * good.price;
}
}
totalPrice = totalPrice.toFixed(2);
this.setData({
'totalCount': totalCount,
'totalPrice': totalPrice
})
},

三、运行效果

微信小程序实战 购物车功能

代码地址如下:
http://www.demodashi.com/demo/12400.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

微信小程序实战 购物车功能的相关教程结束。

《微信小程序实战 购物车功能.doc》

下载本文的Word格式文档,以方便收藏与打印。