<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p>
<button @click="add">添加商品</button>
</p>
<table border="1">
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in shopingCarts">
<td><input v-model="item.goodsName"/></td>
<td><input v-model="item.price"/></td>
<td><input v-model="item.quantity"/></td>
<td>
<button @click="remove(index)">删除</button>
</td>
</tr>
</table>
<p>
<h3>总价: {{totalPrice}} 元</h3></p>
</div>
<script>
new Vue({
el: '#app',
data: {
shopingCarts: [
{goodsName: '', price: '', quantity: ''}
]
},
computed: {
totalPrice: function () {
let total = 0;
this.shopingCarts.forEach(function (item, index) {
let subtotal = item.price * item.quantity;
total += subtotal;
});
return total;
}
},
methods: {
add: function () {
this.shopingCarts.push({goodsName: '', price: '', quantity: ''});
},
remove: function (index) {
this.shopingCarts.splice(index, 1);
}
}
});
</script>
</body>
</html>
computed应用案例
最新推荐文章于 2022-07-07 09:36:14 发布