console
var vue = new Vue({
el:"#app",
data:{
fruits:[
{name:"苹果",size:"大",price:"12"},
{name:"橘子",size:"中",price:"11"},
{name:"香蕉",size:"小",price:"10"},
{name:"西瓜",size:"中",price:"90"},
],
baskets:[
]
},
methods:{
addToBasket(fruit){
let basket = {
name:fruit.name,
size:fruit.size,
price:fruit.price,
quantity:1
}
if(this.baskets.length>0){
let result = this.baskets.filter((basket) =>{
return basket.name === fruit.name&&basket.price===fruit.price
})
if(result != null && result.length>0){
result[0].quantity ++
}else{
this.baskets.push(basket)
}
}else{
this.baskets.push(basket)
}
},
subQuantity(item){
item.quantity --;
if(item.quantity<=0){
this.baskets.splice(this.baskets.indexOf(item),1)
}
},
addQuantity(item){
item.quantity ++
},
emptyBaskets(){
var r = confirm("确定清空购物车?")
if (r== true){
this.baskets = []
}else{
return false
}
}
},
computed:{
total(){
let totalCost = 0
for(var index in this.baskets){
let single = this.baskets[index]
totalCost += single.price * single.quantity
}
return totalCost
}
}
})
<div id="app">
<h3 class="text-center">水果商店</h3>
<table class="table table-default" class="col-sm-12">
<thead class="thead-default">
<tr>
<th>名字</th>
<th>size</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead>
<tbody v-for="fruit in fruits">
<tr>
<td>{{fruit.name}}</td>
<td>{{fruit.size}}</td>
<td>{{fruit.price}}</td>
<td>
<button @click="addToBasket(fruit)" class="btn btn-sm btn-outline-info">+</button>
</td>
</tr>
</tbody>
</table>
<div v-if="this.baskets.length>0">
<h3 class="text-center">购物车</h3>
<table class="table table-default" class="col-sm-12">
<thead class="thead-default">
<tr>
<th>名字</th>
<th>size</th>
<th>单价</th>
<th>操作</th>
<th>价格</th>
</tr>
</thead>
<tbody v-for="item in baskets">
<tr>
<td>{{item.name}}</td>
<td>{{item.size}}</td>
<td>{{item.price}}</td>
<td>
<button class="btn btn-outline-info btn-sm" @click="subQuantity(item)">-</button>
<span>{{item.quantity}}</span>
<button class="btn btn-outline-info btn-sm" @click="addQuantity(item)">+</button>
</td>
<td>{{item.price*item.quantity}}</td>
</tr>
</tbody>
</table>
<p>总价:{{total}} RMB</p>
<button class="btn btn-success btn-block">提交</button>
<button class="btn btn-danger btn-block" @click="emptyBaskets">清空购物车</button>
</div>
<div v-else>
<h3 class="text-center">购物车空空如也</h3>
</div>
</div>