vue 实现购物车总价计算
时间:2021-02-04 11:37:28|栏目:vue|点击: 次
效果如下所示:
js
<script type="text/javascript"> window.οnlοad=function () { var vm = new Vue({ el:'#huo', data:{ myList:[ { number:0, price:23 }, { number:0, price:14.5 }, { number:1, price:8 }, { number:0, price:20 } ], total:0, //总价 bestValue:0 //最贵单价 }, methods:{ //相减 sub:function (item) { item.number--; if(item.number <= 0){ item.number = 0 } this.count() }, //相加 add:function (item) { item.number++; this.count() }, count:function () { var totalPrice = 0;//临时总价 var best = 0;//临时最大单价 this.myList.forEach(function (val,index) { totalPrice += val.number*val.price;//累计总价 //判断最大单价 if(val.price>best && val.number>0){ best = val.price } }); this.total =parseFloat(totalPrice); this.bestValue = parseFloat(best); } }, created:function(){ this.count(); } }) } </script>
html
<div id="huo"> <ul id="list"> <li v-for="item in myList"> <input type="button" value="-" @click="sub(item)"/> <strong>{{item.number}}</strong> <input type="button" value="+" @click="add(item)"/> 单价:<em>{{item.price}}</em> 小计:<span>{{item.number*item.price}}</span> </li> </ul> <p id="p"> 总价:<strong style="margin-right: 20px">{{total}}元</strong> 最贵的单价是:<em>{{bestValue}}元</em> </p> </div>