<template>
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<input type="number" v-model.number="item.quantity" @input="updateQuantity(index, item.quantity)">
</td>
<td>
<button @click="removeFromCart(index)">Remove</button>
</td>
</tr>
</tbody>
</table>
<div>
Total: {{ total }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1', price: 9.99, quantity: 1 },
{ id: 2, name: 'Item 2', price: 19.99, quantity: 2 },
{ id: 3, name: 'Item 3', price: 29.99, quantity: 3 }
]
}
},
computed: {
total() {
return this.items.reduce((sum, item) => sum + item.price * item.quantity, 0)
}
},
methods: {
updateQuantity(index, quantity) {
this.items[index].quantity = quantity
},
removeFromCart(index) {
this.items.splice(index, 1)
}
}
}
</script>
<style>
table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
th, td {
border: 1px solid gray;
padding: 10px;
text-align: left;
}
</style>
上面的代码使用了Vue的v-for指令,将购物车中的商品循环渲染到表格中。同时使用了v-model指令绑定数量的输入值,并使用updateQuantity()方法更新数量。使用removeFromCart()方法实现从购物车中移除商品。最后使用computed属性计算购物车的总价。