vue实现点菜加减
实现点菜加减功能
在Vue中实现点菜加减功能,可以通过数据绑定和事件处理来完成。以下是具体实现方法:
数据准备 在Vue组件的data中定义菜品列表和数量:
data() {
return {
dishes: [
{ id: 1, name: '红烧肉', price: 38, quantity: 0 },
{ id: 2, name: '清蒸鱼', price: 48, quantity: 0 },
{ id: 3, name: '宫保鸡丁', price: 32, quantity: 0 }
]
}
}
模板渲染 使用v-for循环渲染菜品列表,并绑定加减按钮事件:

<div v-for="dish in dishes" :key="dish.id" class="dish-item">
<span>{{ dish.name }} - ¥{{ dish.price }}</span>
<button @click="decrease(dish)">-</button>
<span>{{ dish.quantity }}</span>
<button @click="increase(dish)">+</button>
</div>
方法实现 在methods中定义加减方法:
methods: {
increase(dish) {
dish.quantity++
},
decrease(dish) {
if (dish.quantity > 0) {
dish.quantity--
}
}
}
添加计算总价功能
可以添加一个计算属性来计算总价:

computed: {
totalPrice() {
return this.dishes.reduce((sum, dish) => {
return sum + dish.price * dish.quantity
}, 0)
}
}
在模板中显示总价:
<div class="total-price">
总价: ¥{{ totalPrice }}
</div>
样式优化
添加基本样式美化界面:
.dish-item {
margin: 10px;
padding: 10px;
border: 1px solid #eee;
display: flex;
align-items: center;
}
.dish-item button {
margin: 0 5px;
padding: 2px 10px;
}
.total-price {
margin-top: 20px;
font-weight: bold;
font-size: 18px;
}
完整组件示例
<template>
<div>
<div v-for="dish in dishes" :key="dish.id" class="dish-item">
<span>{{ dish.name }} - ¥{{ dish.price }}</span>
<button @click="decrease(dish)">-</button>
<span>{{ dish.quantity }}</span>
<button @click="increase(dish)">+</button>
</div>
<div class="total-price">
总价: ¥{{ totalPrice }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
dishes: [
{ id: 1, name: '红烧肉', price: 38, quantity: 0 },
{ id: 2, name: '清蒸鱼', price: 48, quantity: 0 },
{ id: 3, name: '宫保鸡丁', price: 32, quantity: 0 }
]
}
},
methods: {
increase(dish) {
dish.quantity++
},
decrease(dish) {
if (dish.quantity > 0) {
dish.quantity--
}
}
},
computed: {
totalPrice() {
return this.dishes.reduce((sum, dish) => {
return sum + dish.price * dish.quantity
}, 0)
}
}
}
</script>
<style>
.dish-item {
margin: 10px;
padding: 10px;
border: 1px solid #eee;
display: flex;
align-items: center;
}
.dish-item button {
margin: 0 5px;
padding: 2px 10px;
}
.total-price {
margin-top: 20px;
font-weight: bold;
font-size: 18px;
}
</style>






