Vue(小案例_vue+axios仿手机app)_购物车(计算商品总金额)

时间:2023-03-08 19:47:38

一、前言

                1、计算总金额

                2、点击删除按钮,删除对应的商品信息

                3、当还没结算的时候,当用户跳到其他页面时,提示用户是否要离开

二、主要内容

1、计算总金额

(1)效果演示:

Vue(小案例_vue+axios仿手机app)_购物车(计算商品总金额)

  (2)监听多个属性用到computed计算属性

computed:{
payment(){
let total = 0;//定义总金额
let count =0;//定义总数量 this.shopCart.forEach((shop)=>{ if(shop.isSelected){//当上面的按钮勾上了,才计算
count = count+shop.num;
total = total + shop.num * shop.sell_price;
}
}) return {
total, count
}
}
},

2、点击删除按钮,删除对应的商品信息

  删除操作可以用splice, delete

del(shop,index){//将当前的对象,和index传进来
this.shopCart.splice(index,1)//数组中的当前对象 }

3、当还没结算的时候,当用户跳到其他页面时,提示用户是否要离开

  (1)用导航守卫,在路由离开之前给用户提示

beforeRouteLeave(to, from, next){
let res = confirm("确定要离开吗"); if(res){
//保存用户编辑的数据
let obj={};
this.shopCart.forEach((shop)=>{
obj[shop.id]=shop.num
}) GoodsTool.saveGoods(obj);
next();//然后放行
}else{
next(false);//取消,
}
}

三、总结