当前位置:首页 > 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中实现菜单功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for动态生成菜单 通过数据驱动的方式动态渲染菜单项,适合菜单内容可能变化的场景: <t…

css菜单制作

css菜单制作

基础水平菜单制作 使用无序列表<ul>和<li>标签构建结构,CSS设置横向排列: <ul class="horizontal-menu"> <li&…

css div 制作导航菜单

css div 制作导航菜单

基本导航菜单结构 使用HTML创建一个简单的导航菜单结构,通常使用<ul>和li>列表实现。每个菜单项用<a>标签包裹以实现链接功能。 <div class="n…

vue实现菜单调用

vue实现菜单调用

Vue 实现动态菜单调用的方法 使用路由配置生成菜单 在 Vue 项目中,可以通过路由配置自动生成菜单结构。路由配置通常包含 path、name、meta 等信息,这些信息可用于构建菜单项。 //…

vue无限菜单怎么实现

vue无限菜单怎么实现

Vue 无限级菜单的实现 实现无限级菜单通常需要递归组件和动态数据结构的结合。以下是具体实现方法: 数据结构设计 采用嵌套结构表示菜单层级,每个菜单项包含 children 属性存储子菜单:…

vue 菜单实现

vue 菜单实现

Vue 菜单实现方法 基于路由的动态菜单 在 Vue 项目中,可以利用 Vue Router 实现动态菜单。首先定义路由配置,包含菜单所需的元信息(如标题、图标等)。 const routes =…