这篇文章主要介绍js如何实现购物车计算,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
具体内容如下
以店铺为单位,每个店铺下面有对应的商品选项,可全选,商品单选,店铺单选,商品数量加减,删除
代码:
<script>
export default {
data() {
return {
count:0, //所有商品的数量和
shopCarList: [], //所有商品
selectList:[] //已选择的商品
}
},
computed: {
//选择的合计价格
selectPrice(){
return this.selectList.reduce((total,item,index)=>{
return total+item.quantity*(item.activityPrice || item.price);
},0)
},
//选择的合计数量
selectNum(){
return this.selectList.reduce((total,item,index)=>{
return total+item.quantity;
},0)
},
//是否全选
isSelecetAll(){
return this.shopCarList.every(item=>{
return item.shopSelect===true
})
}
},
methods: {
//增加
increment(itm){
itm.quantity<itm.stock?itm.quantity++:'';
},
//减少
decrement(itm){
itm.quantity>1?itm.quantity--:''
},
//全选点击
allChooseHandle(){
this.initSelectAll(!this.isSelecetAll);
},
//商品单选点击
productChooseHandle(itm,index){
let productFlag = !itm.productSelect;
this.$set(itm,'productSelect',productFlag);
let shopFlag = this.shopCarList[index].products.every(i=>{
return i.productSelect===true;
})
this.$set(this.shopCarList[index],'shopSelect',shopFlag);
this.getSelected();
},
//店铺单选点击
shopChooseHandle(item,index){
let Flag = !item.shopSelect;
this.$set(item,'shopSelect',Flag);
item.products.forEach((itm,idx)=>{
this.$set(itm,'productSelect',Flag);
})
this.getSelected();
},
//获取已选商品
getSelected(){
let tempArr = [];
this.shopCarList.forEach((item,index)=>{
item.products.forEach((itm,idx)=>{
if(itm.productSelect){
tempArr.push(itm);
}
})
})
this.selectList = tempArr;
},
//是否全选初始化
initSelectAll(Flag){
this.shopCarList.forEach((item,index)=>{
this.$set(item,'shopSelect',Flag);
item.products.forEach((itm,idx)=>{
this.$set(itm,'productSelect',Flag);
})
})
this.getSelected();
},
//获取购物车列表
getCarList(){
return this.$api.personal.getCarList().then(res=>{
if(res.result==='000'){
//过期商品数
let expiredNum = 0;
res.data.expiredList.forEach(item=>{
item.products.forEach(itm=>{
expiredNum += itm.quantity
})
})
//有效商品数量
this.count = res.data.count - expiredNum;
this.shopCarList = res.data.shopCarList;
return Promise.resolve()
}
})
},
//删除点击
delCarList(itm,index,idx){
this.$api.personal.delCarList( [itm.carId] ).then(res=>{
if(res.result==='000'){
this.count -= itm.quantity;
this.shopCarList[index].products.splice(idx,1);
if(this.shopCarList[index].products.length===0){
this.shopCarList.splice(index,1);
}
this.getSelected();
}
})
},
},
created() {
this.getCarList().then(()=>{
this.initSelectAll(true);
});
},
};
</script>
以上是“js如何实现购物车计算”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。