vue实现点菜加减

实现点菜加减功能
在Vue中实现点菜加减功能,可以通过数据绑定和事件处理来完成。以下是一个完整的实现示例:
创建Vue实例和数据
new Vue({
el: '#app',
data: {
dishes: [
{ id: 1, name: '鱼香肉丝', price: 28, count: 0 },
{ id: 2, name: '宫保鸡丁', price: 32, count: 0 },
{ id: 3, name: '水煮鱼', price: 45, count: 0 }
]
},
methods: {
increment(index) {
this.dishes[index].count++
},
decrement(index) {
if (this.dishes[index].count > 0) {
this.dishes[index].count--
}
}
},
computed: {
totalPrice() {
return this.dishes.reduce((sum, dish) => sum + dish.price * dish.count, 0)
}
}
})
HTML模板
<div id="app">
<div v-for="(dish, index) in dishes" :key="dish.id" class="dish-item">
<span>{{ dish.name }} - ¥{{ dish.price }}</span>
<button @click="decrement(index)">-</button>
<span>{{ dish.count }}</span>
<button @click="increment(index)">+</button>
</div>
<div class="total">
总计: ¥{{ totalPrice }}
</div>
</div>
CSS样式
.dish-item {
margin: 10px;
padding: 10px;
border: 1px solid #ddd;
display: flex;
align-items: center;
}
.dish-item button {
width: 30px;
height: 30px;
margin: 0 5px;
}
.total {
margin-top: 20px;
font-size: 18px;
font-weight: bold;
}
功能说明
- 使用v-for指令循环渲染菜品列表
- 每个菜品包含名称、价格和数量
- 点击+按钮增加数量,点击-按钮减少数量
- 计算属性totalPrice实时计算总价
- 数量不会减少到负数以下
扩展功能
可以添加更多功能来完善点菜系统:
// 添加清空功能
methods: {
clearAll() {
this.dishes.forEach(dish => dish.count = 0)
}
}
// 添加提交订单功能
methods: {
submitOrder() {
const selectedDishes = this.dishes.filter(dish => dish.count > 0)
if (selectedDishes.length === 0) {
alert('请至少选择一道菜')
return
}
// 发送订单数据到服务器
console.log('提交订单:', selectedDishes)
}
}







