700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 微信小程序实战 购物车功能

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

时间:2020-04-20 04:21:58

相关推荐

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

代码地址如下:

/demo/12400.html

一、准备工作

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

官方下载地址:https://mp./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/12400.html

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。