数据结构
Let list = [
{
id: 1,
goods_name: "九江双蒸 29.5°地道米酒 500ml*12瓶"
num: 2,
price: 120
},
{
id: 1,
goods_name: "天龙泉35度 500ml*6瓶"
num: 1,
price: 90
},
]
<view wx:for='{
{list}}' wx:key='index' class='card'>
<radio checked="{
{item.isSelect}}"
color="#c50c1e"
bindtap="radioSelect"
id='{
{index}}'
data-isSelect='{
{item.isSelect|| false}}'>
radio>
view>
对应的单选功能
// 单选
radioSelect(e) {
let index = e.currentTarget.id;
this.setData({
['list['+index+'].isSelect']: !e.currentTarget.dataset.isSelect
});
this.selectAllCheck(); // 是否全选
},
<radio checked="{
{isSelectAll}}"
color="#c50c1e"
bindtap="radioSelectALL">全选
radio>
对应的全选功能
// 全选
radioSelectALL() {
let isSelectAll = !this.data.isSelectAll;
let list = this.data.list;
list.forEach(item =>item.isSelect = isSelectAll);
this.setData({
isSelectAll,
list
})
},
全选检查// 单选要检查是否已单选完所有选项
// 是否全选
selectAllCheck() {
let isSelectAll = !this.data.list.filter(item =>!item.isSelect).length;
if (this.data.isSelectAll != isSelectAll){
this.setData({
isSelectAll
})
}
},
<view style="color:red;">共计:{
{total||0.00}}元view>
对应计价功能
函数reduce有两个位置参数,第一个是累加器,另一个是迭代值,它返回累加值
// 计价
calculateTotalPrice() {
let total = 0;
let list = this.data.list.filter(item =>item.isSelect);
total = list.reduce((sum, x) => sum + x.price*x.num, 0);
this.setData({
total: total.toFixed(2)
})
},
先筛选获取已选的选项,总价为选项的单价*数量,累计起来 =>或是这样:
// 计价
calculateTotalPrice() {
let total = 0;
let goods = this.data.list;
for(let i in goods) {
if (goods[i].isSelect) {
total+= goods[i].price*goods[i].num;
}
}
this.setData({
total: total.toFixed(2)
})
},
<view class='num-box'>
<p bindtap='increaseOrDecrease' id='-1' data-index='{
{index}}'>-p>
<input value="{
{item.num}}"
placeholder="1"
type='number'
maxlength="3"
bindblur="userInput"
data-index="{
{index}}">
input>
<p bindtap='increaseOrDecrease' id='1' data-index='{
{index}}'>+p>
view>
对应的加减
// 数量增减按钮
increaseOrDecrease(e) {
let index = e.currentTarget.dataset.index;
let item = this.data.list[index];
let number = ~~item.num + ~~e.currentTarget.id;
this.setData({
['list['+index+'].num']: number>0?number:1
});
// TODO 提交后台更新数量...
// 如果选中就重新计价...
},
// 数量输入
userInput(e) {
let number = e.detail.value;
let index = e.currentTarget.dataset.index;
if (!number||number<1||isNaN(number)) number = 1; // 输入校验
this.setData({
['list['+index+'].num']: number
});
// TODO 提交后台更新数量...
// 如果选中就重新计价...
},
// 删除
deleteCartItem() {
// 是否勾选有商品....
wx.showModal({
cancelColor: '提示!',
content: '是否要删除该商品?',
success: res =>{
if (res.confirm) {
wx.showLoading({
title:'正在删除'});
let list = this.data.list;
for (let i = 0; i < list.length; i++) {
if (list[i].isSelect) {
// TODO 请求后台删除...
list.splice(i, 1);
i--;
}
}
this.setData({
list});
}
}
})
},