用vue实现菜单下单
Vue 实现菜单下单功能
数据结构设计
菜单数据通常以数组形式存储,每个菜品包含名称、价格、描述等信息:
data() {
return {
menuItems: [
{ id: 1, name: '红烧肉', price: 38, description: '经典家常菜' },
{ id: 2, name: '清蒸鱼', price: 48, description: '鲜嫩可口' }
],
cart: []
}
}
菜单展示组件
使用 v-for 渲染菜单列表,每个菜品添加加入购物车按钮:
<div v-for="item in menuItems" :key="item.id" class="menu-item">
<h3>{{ item.name }}</h3>
<p>{{ item.description }}</p>
<span>¥{{ item.price }}</span>
<button @click="addToCart(item)">加入购物车</button>
</div>
购物车功能实现
添加菜品到购物车的方法,处理重复菜品数量累加:

methods: {
addToCart(item) {
const existingItem = this.cart.find(cartItem => cartItem.id === item.id)
if (existingItem) {
existingItem.quantity++
} else {
this.cart.push({ ...item, quantity: 1 })
}
}
}
购物车展示组件
显示已选菜品和总价,提供删除和调整数量功能:
<div class="cart">
<div v-for="(item, index) in cart" :key="item.id">
{{ item.name }} x {{ item.quantity }} = ¥{{ item.price * item.quantity }}
<button @click="decreaseQuantity(index)">-</button>
<button @click="increaseQuantity(index)">+</button>
<button @click="removeItem(index)">删除</button>
</div>
<div>总计: ¥{{ totalPrice }}</div>
</div>
计算属性
计算购物车总价:

computed: {
totalPrice() {
return this.cart.reduce((total, item) => {
return total + (item.price * item.quantity)
}, 0)
}
}
下单功能
添加提交订单方法,可连接后端API:
methods: {
submitOrder() {
const order = {
items: this.cart,
total: this.totalPrice,
timestamp: new Date()
}
// 实际项目中这里调用API接口
console.log('提交订单:', order)
this.cart = [] // 清空购物车
alert('订单已提交')
}
}
样式优化
添加基础CSS样式提升用户体验:
.menu-item {
border: 1px solid #ddd;
padding: 10px;
margin: 10px;
display: inline-block;
width: 200px;
}
.cart {
position: fixed;
right: 0;
top: 0;
width: 300px;
background: #f5f5f5;
padding: 20px;
}
这个实现包含了菜单展示、购物车管理和订单提交的基本功能,可根据实际需求扩展更多特性如菜品分类、优惠计算等。






