JS实现购物车的简单原理

                                                                  ***vue实现购物车原理***

思路:
1.是否选中
2.数量的加减
3.计算总数量
4.计算总价

思路一:

//判断是否选中和是否全选(我的单选框是自定义的)
checked (item) {
// 点击的时候判断当前是选中还是未选中
item.checked = !item.checked
let newAllCheck = this.dataList.filter(a => a.checked == true)
if (newAllCheck.length == this.dataList.length) {
this.allChecked = true
} else {
this.allChecked = false
}
if (item.checked == true) {
this.collArr.push(item.sid)
this.coll_id = this.collArr
} else {
this.coll_id = this.collArr.splice(this.dataList.indexOf(this.dataList.filter(f => f.checked == false).map(s => s.sid)), 1)
}
this.totalSum();
},
allCheck (allcheck) {
this.allChecked = !allcheck
if (this.allChecked == true) {
this.dataList.forEach(f => {
f.checked = true
})
this.coll_id.push(this.dataList.map(m => m.sid))
} else {
this.dataList.forEach(f => {
f.checked = false
})
this.coll_id = [];
this.totleMoney = 0;
}
this.totalSum();
},
//计算整个页面所有购物车列表的金额
totalSum(){
//计算整个页面的金额
var sumMoney = 0;
this.dataList.forEach(element =>{
if(element.checked == true){
sumMoney += element.good_price * element.quantity;
}
})
this.totleMoney = sumMoney;
},

//数量的加减,参数1是判断价或者减参数2是当前点击的商品的下标
changeNum (x,index) {
if (x == 1) {
var num = Number(this.dataList[index].quantity);
if(num > 1) {
num = num - 1;
this.dataList[index].quantity = num;
}
this.totalSum();
} else if (x == 2) {
var num = Number(this.dataList[index].quantity);
num = num + 1;
this.dataList[index].quantity = num;
this.totalSum();
}
}

//created钩子函数中调用一下计算页面总数的函数,就OK了,

以上是我自己实现购物车的方法,希望能够帮助大家,共勉

你可能感兴趣的:(JS实现购物车的简单原理)