注意:
1、浮点四舍五入问题。moneyCount.toFixed(2);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>购物车-Vue</title> <script> </script> </head> <body> <div id="div1" style="border: 1px"> <fieldset> <legend>{{userName}}的购物车</legend> <table border="1"> <thead> <tr> <th>行号</th> <th>编码</th> <th>名称</th> <th>单价</th> <th>数量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(goods,index) in goodsWillPay"> <td>{{index+1}}</td> <td>{{goods.goodsNo}}</td> <td>{{goods.goodsName}}</td> <td>{{goods.goodsPrice}}</td> <td><button @click="changeRowQuantity(index,'-')">-</button> {{goods.goodsQuantity}} <button @click="changeRowQuantity(index,'+')">+</button> </td> <td :class="'text-center'"><button @click="DeleteGoodsRow(index)">移除</button> </td> </tr> </tbody> </table> <label>合计金额:</label><span>{{countGoodsMoney()}}</span> </fieldset> </div> </body> <script src="js/vue.js"></script> <script> var goodsList={ userName:"“杨胜利”", goodsWillPay:[{goodsNo:"sp001",goodsName:"iPhone X",goodsPrice:7999.99,goodsQuantity:1}, {goodsNo:"sp008",goodsName:"荣耀 10", goodsPrice:2399.00,goodsQuantity:1}, {goodsNo:"sp009",goodsName:"华为 P20",goodsPrice:3399.00,goodsQuantity:1}, {goodsNo:"sp012",goodsName:"小米 8", goodsPrice:3999.00,goodsQuantity:1}] }; var v1= new Vue({ el:'#div1', data:goodsList, methods:{ // 统计购物车中的商品金额之和 countGoodsMoney:function(){ let moneyCount=0; for (var i=0;i<this.goodsWillPay.length;i++){ console.log((i+1) +"行 moneyCount:"+ this.goodsWillPay[i].goodsPrice * this.goodsWillPay[i].goodsQuantity); moneyCount=moneyCount + this.goodsWillPay[i].goodsPrice* this.goodsWillPay[i].goodsQuantity; moneyCount.toFixed(2); } return moneyCount.toFixed(2); }, // 修改指定商品行的数量:加1或减1 changeRowQuantity:function (index,addOrSubtraction) { console.log("index:"+ index); console.log("addOrSubtraction:"+ addOrSubtraction); if (addOrSubtraction=="-" ){ if (this.goodsWillPay[index].goodsQuantity>0){ this.goodsWillPay[index].goodsQuantity = this.goodsWillPay[index].goodsQuantity -1; } } if (addOrSubtraction=="+" ){ this.goodsWillPay[index].goodsQuantity = this.goodsWillPay[index].goodsQuantity + 1; } }, //从购物车,移除一行商品 DeleteGoodsRow:function (index) { this.goodsWillPay.splice(index,1); }, } }); </script> </html>