总价随着购买数量的变化自动算出,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<style type="text/css">
table {
border: 1px solid black;
width: 80%;
margin-left: 10%;
}
th {
height: 50px;
}
th, td {
border-bottom: 1px solid #ddd;
text-align: center;
}
td button{
display: inline-block;
}
</style>
</head>
<body>
<div id="root">
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="good in goods">
<td>{{good.id}}</td>
<td>{{good.name}}</td>
<td>{{good.price}}</td>
<td>
<button v-bind:disabled="good.count==0" @click="good.count-=1">-</button>
{{good.count}}
<button @click="good.count+=1">+</button>
</td>
<td><button @click="good.count=0">移除</button></td>
</tr>
</table>
总价:¥{{totalPrice()}}
</div>
<script>
new Vue({
el:'#root',
data:{
goods:[{
id:1,
name:"iphone",
price:5000,
count:1
},
{
id:2,
name:"iphone xs",
price:6000,
count:1
},
{
id:3,
name:"iphone xr",
price:7000,
count:1
}
,]
},
methods:{
totalPrice:function(){
var totalP=0;
for (var i=0;i<this.goods.length;i++) {
totalP+=this.goods[i].price*this.goods[i].count;
}
return totalP;
}
}
})
</script>
</body>
</html>