運(yùn)行效果
項(xiàng)目demo
一侧到、準(zhǔn)備工作
基本需求
顯示圖書(shū)基本信息:名稱(chēng)勃教、作者、描述床牧、價(jià)格荣回、數(shù)量遭贸。
點(diǎn)擊復(fù)選框進(jìn)行toggle操作戈咳。當(dāng)前選中,則變成未選中壕吹;當(dāng)前未選中著蛙,則變成選中。
圖書(shū)數(shù)量的加減操作耳贬。
根據(jù)選中商品進(jìn)行價(jià)格匯總踏堡。
全選/全不選。
目錄結(jié)構(gòu)
二咒劲、程序?qū)崿F(xiàn)步驟
復(fù)選框進(jìn)行toggle操作顷蟆。當(dāng)前選中诫隅,則變成未選擇;當(dāng)前未選中帐偎,則變成選中逐纬。購(gòu)物車(chē)商品全部選中,全選按鈕為選中狀態(tài)削樊。購(gòu)物車(chē)商品全部未選中豁生,全選按鈕為未選中狀態(tài)。
/**
* 用戶(hù)選擇購(gòu)物車(chē)商品
*/
checkboxChange: function (e) {
console.log('checkbox發(fā)生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();
},
商品的加減操作甸箱。當(dāng)前數(shù)量大于1颖系,可以進(jìn)行加減操作锁孟;當(dāng)前數(shù)量為1時(shí)谬擦,只能進(jìn)行加操作是己。
/**
* 用戶(hù)點(diǎn)擊商品減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();
}
},
/**
* 用戶(hù)點(diǎn)擊商品加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();
},
用戶(hù)點(diǎn)擊全選/全不選旅掂,遍歷購(gòu)物車(chē)所有商品設(shè)置當(dāng)前選中狀態(tài)州既。
/**
* 用戶(hù)點(diǎn)擊全選
*/
selectalltap: function (e) {
console.log('用戶(hù)點(diǎn)擊全選锨阿,攜帶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();
}
選中商品數(shù)量發(fā)生改變時(shí)酣衷,進(jìn)行商品總數(shù)量和總價(jià)格的計(jì)算树碱。
/**
* 計(jì)算商品總數(shù)
*/
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
})
},