目录
任务描述:
点击数量按钮实现商品数量的变化,同时商品的总价和合计金额随之发生改变。此外,当商品的数量小于1时触发弹窗警告。
效果图:
代码如下:
<body>
<div id="shoppingCart">
<table >
<thead>
<tr>
<th>
名称
</th>
<th>
单价
</th>
<th>
数量
</th>
<th>
总价
</th>
</tr>
</thead>
<tbody>
<tr v-for="(value, index) in phoneInfo">
<th>
{{value.name}}
</th>
<th>
{{value.price}}
</th>
<th>
<button @click="sub(index)">-</button>
<input type="text" v-model="value.count">
<button @click="add(index)">+</button>
</th>
<th>
{{value.price * value.count}}
</th>
</tr>
<tr>
<th>
合计:{{calu}}
</th>
</tr>
</tbody>
</table>
</div>
<script>
var vm = new Vue({
el: '#shoppingCart',
data: {
phoneInfo: [
{
name: '商品01',
price: 12345,
count: 1
},
{
name: '商品02',
price: 23456,
count: 1
}
]
},
computed: {
calu: function () {
var total = 0;
this.phoneInfo.forEach(function (s) {
total += s.price * s.count;
});
retuen total;
}
},
methods: {
add: function (index) {
this.phoneInfo[index].count++;
},
sub: function (index) {
if (this.phoneInfo[index].count > 1) {
this.phoneInfo[index].count--;
} else {
alert("数量不能为0");
}
}
}
})
</script>
</body>
觉得还不错就给个赞吧!