1.data
/**
* 頁面的初始資料
*/
data: {
hasList: true,//購物車是否為空
totalPrice: 0, // 總價
selectAllStatus: true,//全選狀态
items: [{ checked: false}],
cartList: [] // 商品清單
},
2.數量編輯
<!-- wxml -->
<view class="stepper">
<!-- 減号 -->
<text
class="sign {{num <= 1 ? 'disabled' : 'normal'}}"
bindtap="delCount"
data-index="{{index}}">-</text>
<!-- 數值 -->
<input
class="number"
type="number"
data-index="{{index}}"
bindchange="bindManual" value="{{item.number}}"
/>
<!-- 加号 -->
<text
class="sign {{num >= 10 ? 'disabled' : 'normal'}}"
bindtap="addCount" data-index="{{index}}">+</text>
</view>
/* js */
/* 點選減号 */
delCount: function (e) {
const index = e.target.dataset.index
let num = this.data.cartList[index].number;
// 如果大于1時,才可以減
if (num > 1) {
num--;
}
// 隻有大于一件的時候,才能normal狀态,否則disable狀态
var minusStatus = num <= 1 ? 'disabled' : 'normal';
// 将數值與狀态寫回
const number = 'cartList[' + index + '].number'
this.setData({
[number]: num,
minusStatus: minusStatus
});
this.getTotalPrice()
},
/* 點選加号 */
addCount: function (e) {
console.log(e)
const index = e.target.dataset.index
let num = this.data.cartList[index].number;
// 不作過多考慮自增1
num++;
// 隻有大于一件的時候,才能normal狀态,否則disable狀态
let minusStatus = num < 1 ? 'disabled' : 'normal';
// 将數值與狀态寫回
const number = 'cartList[' + index + '].number'
this.setData({
[number]: num,
minusStatus: minusStatus
});
this.getTotalPrice()
},
/* 輸入框事件 */
bindManual: function (e) {
console.log(e)
const index = e.currentTarget.dataset.index
const number = 'cartList[' + index + '].number'
var num = e.detail.value;
// 将數值與狀态寫回
this.setData({
[number]: num
});
this.getTotalPrice()
console.log(this.data.cartList)
},
3.單條資料的選中和全選
// 計算總價
getTotalPrice() {
let carts = this.data.cartList; // 擷取購物車清單
let total = 0;
for (let i = 0; i < carts.length; i++) { // 循環清單得到每個資料
if (carts[i].checked) { // 判斷選中才會計算價格
total += carts[i].number * carts[i].price; // 所有價格加起來
}
}
this.setData({ // 最後指派到data中渲染到頁面
cartList: carts,
totalPrice: total.toFixed(2)
});
},
// 全選
checkAll: function () {
let selectAllStatus = this.data.selectAllStatus
selectAllStatus = !selectAllStatus
let cartList = this.data.cartList
console.log(111,cartList)
for(let i = 0;i<cartList.length;i++){
cartList[i].checked = selectAllStatus
}
this.setData({
selectAllStatus: selectAllStatus,
cartList: cartList
})
this.getTotalPrice()
},
// 點選選擇按鈕切換選中狀态
checkboxChange: function (e) {
const that = this
const index = e.currentTarget.dataset.index
const cartList = 'cartList[' + index +'].checked'
that.setData({
[cartList]: e.detail.value.length > 0 ? true : false
});
let arr = this.data.cartList.filter(v => {
return v.checked === false
})
// 當清單切換狀态時,相應的改變全選狀态
this.setData({
selectAllStatus: arr.length?false:true
})
this.getTotalPrice()
},