当前位置:首页 > VUE

用vue实现菜单下单

2026-01-22 16:31:18VUE

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>

购物车功能实现

添加菜品到购物车的方法,处理重复菜品数量累加:

用vue实现菜单下单

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>

计算属性

计算购物车总价:

用vue实现菜单下单

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;
}

这个实现包含了菜单展示、购物车管理和订单提交的基本功能,可根据实际需求扩展更多特性如菜品分类、优惠计算等。

标签: 下单菜单
分享给朋友:

相关文章

vue实现导航菜单

vue实现导航菜单

Vue 实现导航菜单的方法 基础路由导航实现 在 Vue 项目中,使用 vue-router 可以轻松实现导航菜单功能。首先安装并配置路由: npm install vue-router 在 rou…

vue实现左右菜单联动实现

vue实现左右菜单联动实现

Vue 实现左右菜单联动 数据绑定与状态管理 在 Vue 中实现左右菜单联动,核心是通过共享状态或事件通信实现数据同步。可以通过 Vuex 或组件间的 props/emit 机制管理联动状态。 //…

vue实现菜单权限

vue实现菜单权限

基于路由的动态菜单权限控制 在Vue中实现菜单权限通常需要结合路由配置和用户角色/权限数据。以下是常见的实现方法: 路由配置中添加权限标识 // router.js const routes =…

vue 实现多级菜单

vue 实现多级菜单

Vue 实现多级菜单的方法 递归组件实现 递归组件是处理多级菜单的常见方式,通过组件调用自身实现无限层级嵌套。 <template> <ul> <li v-…

vue  简单菜单实现

vue 简单菜单实现

实现简单菜单的步骤 在 Vue 中实现一个简单的菜单,可以通过以下方法完成: 使用 v-for 动态渲染菜单项 在 Vue 的模板中,使用 v-for 遍历菜单数据,动态生成菜单项。 <…

vue  实现多级菜单

vue 实现多级菜单

实现多级菜单的基本思路 在Vue中实现多级菜单通常需要递归组件或动态渲染嵌套数据结构。核心是通过组件递归调用自身,或利用v-for遍历嵌套的菜单数据。 递归组件实现方式 定义菜单数据结构 数据格式…