vue实现点菜加减
实现点菜加减功能
在Vue中实现点菜加减功能,通常需要以下步骤:
数据模型设计
data() {
return {
dishes: [
{ id: 1, name: '鱼香肉丝', price: 28, count: 0 },
{ id: 2, name: '宫保鸡丁', price: 32, count: 0 }
]
}
}
加减方法实现

methods: {
increaseCount(dish) {
dish.count++
},
decreaseCount(dish) {
if (dish.count > 0) {
dish.count--
}
}
}
模板部分
<div v-for="dish in dishes" :key="dish.id">
<span>{{ dish.name }}</span>
<span>¥{{ dish.price }}</span>
<button @click="decreaseCount(dish)">-</button>
<span>{{ dish.count }}</span>
<button @click="increaseCount(dish)">+</button>
</div>
计算总价功能
添加计算总价的方法:

computed: {
totalPrice() {
return this.dishes.reduce((sum, dish) => {
return sum + dish.price * dish.count
}, 0)
}
}
在模板中显示总价:
<div>总价:¥{{ totalPrice }}</div>
样式优化
为加减按钮添加样式:
button {
width: 30px;
height: 30px;
border-radius: 50%;
border: 1px solid #ccc;
background: #fff;
cursor: pointer;
}
button:hover {
background: #f5f5f5;
}
完整组件示例
<template>
<div class="menu">
<div v-for="dish in dishes" :key="dish.id" class="dish-item">
<span class="name">{{ dish.name }}</span>
<span class="price">¥{{ dish.price }}</span>
<button @click="decreaseCount(dish)">-</button>
<span class="count">{{ dish.count }}</span>
<button @click="increaseCount(dish)">+</button>
</div>
<div class="total">总价:¥{{ totalPrice }}</div>
</div>
</template>
<script>
export default {
data() {
return {
dishes: [
{ id: 1, name: '鱼香肉丝', price: 28, count: 0 },
{ id: 2, name: '宫保鸡丁', price: 32, count: 0 },
{ id: 3, name: '水煮鱼', price: 45, count: 0 }
]
}
},
methods: {
increaseCount(dish) {
dish.count++
},
decreaseCount(dish) {
if (dish.count > 0) {
dish.count--
}
}
},
computed: {
totalPrice() {
return this.dishes.reduce((sum, dish) => {
return sum + dish.price * dish.count
}, 0)
}
}
}
</script>
<style>
.menu {
width: 300px;
margin: 20px auto;
}
.dish-item {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.name {
flex: 2;
}
.price {
flex: 1;
text-align: right;
margin-right: 15px;
}
.count {
width: 30px;
text-align: center;
}
button {
width: 30px;
height: 30px;
border-radius: 50%;
border: 1px solid #ccc;
background: #fff;
cursor: pointer;
}
button:hover {
background: #f5f5f5;
}
.total {
margin-top: 20px;
text-align: right;
font-weight: bold;
}
</style>
这个实现包含了基本的点菜加减功能,并提供了总价计算和简单样式。可以根据实际需求进一步扩展功能,如添加菜品图片、分类显示等。






