微信小程序实战 购物车功能
一、准备工作
软件环境:微信开发者工具
官方下载地址: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
})
},
三、运行效果
微信小程序实战 购物车功能
注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?