vue实现点菜
Vue实现点菜功能
使用Vue实现点菜功能可以结合组件化开发、状态管理和事件处理。以下是一个简单的实现方案:
数据结构设计
data() {
return {
menuItems: [
{ id: 1, name: '鱼香肉丝', price: 38, selected: false },
{ id: 2, name: '宫保鸡丁', price: 42, selected: false },
{ id: 3, name: '水煮鱼', price: 68, selected: false }
],
cart: []
}
}
模板部分

<div class="menu">
<div v-for="item in menuItems" :key="item.id" class="menu-item">
<h3>{{ item.name }}</h3>
<p>价格: {{ item.price }}元</p>
<button @click="addToCart(item)">加入购物车</button>
</div>
</div>
<div class="cart">
<h2>已点菜品</h2>
<ul>
<li v-for="(item, index) in cart" :key="index">
{{ item.name }} - {{ item.price }}元
<button @click="removeFromCart(index)">移除</button>
</li>
</ul>
<p>总计: {{ totalPrice }}元</p>
</div>
方法实现
methods: {
addToCart(item) {
this.cart.push({...item})
item.selected = true
},
removeFromCart(index) {
const removedItem = this.cart[index]
const menuItem = this.menuItems.find(item => item.id === removedItem.id)
if(menuItem) menuItem.selected = false
this.cart.splice(index, 1)
}
},
computed: {
totalPrice() {
return this.cart.reduce((sum, item) => sum + item.price, 0)
}
}
进阶功能实现
分类显示菜品

data() {
return {
categories: [
{ id: 1, name: '热菜' },
{ id: 2, name: '凉菜' }
],
menuItems: [
{ id: 1, name: '鱼香肉丝', price: 38, categoryId: 1 },
{ id: 2, name: '拍黄瓜', price: 18, categoryId: 2 }
]
}
}
数量选择功能
methods: {
addToCart(item) {
const existingItem = this.cart.find(cartItem => cartItem.id === item.id)
if(existingItem) {
existingItem.quantity++
} else {
this.cart.push({...item, quantity: 1})
}
}
}
状态管理方案
对于更复杂的点菜系统,可以考虑使用Vuex:
// store.js
const store = new Vuex.Store({
state: {
menuItems: [],
cart: []
},
mutations: {
ADD_TO_CART(state, item) {
state.cart.push(item)
},
REMOVE_FROM_CART(state, index) {
state.cart.splice(index, 1)
}
},
actions: {
addToCart({ commit }, item) {
commit('ADD_TO_CART', item)
}
},
getters: {
totalPrice: state => {
return state.cart.reduce((sum, item) => sum + item.price, 0)
}
}
})
UI优化建议
使用Element UI或Vant等UI框架可以快速构建美观的界面:
<el-card v-for="item in menuItems" :key="item.id">
<div slot="header">
<span>{{ item.name }}</span>
</div>
<div>
<p>价格: {{ item.price }}元</p>
<el-button type="primary" @click="addToCart(item)">点菜</el-button>
</div>
</el-card>
实现点菜功能时,需要根据实际需求考虑菜品分类、规格选择、口味备注等扩展功能。对于餐厅系统,可能还需要对接后厨打印、桌台管理等功能模块。






