vue購物車總價計算
阿新 • • 發佈:2019-02-16
js
<script type="text/javascript">
window.onload=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>