当前位置:首页 > VUE

vue实现点菜加减

2026-02-18 16:58:36VUE

vue实现点菜加减

实现点菜加减功能

在Vue中实现点菜加减功能,可以通过数据绑定和事件处理来完成。以下是一个完整的实现示例:

vue实现点菜加减

创建Vue实例和数据

new Vue({
  el: '#app',
  data: {
    dishes: [
      { id: 1, name: '鱼香肉丝', price: 28, count: 0 },
      { id: 2, name: '宫保鸡丁', price: 32, count: 0 },
      { id: 3, name: '水煮鱼', price: 45, count: 0 }
    ]
  },
  methods: {
    increment(index) {
      this.dishes[index].count++
    },
    decrement(index) {
      if (this.dishes[index].count > 0) {
        this.dishes[index].count--
      }
    }
  },
  computed: {
    totalPrice() {
      return this.dishes.reduce((sum, dish) => sum + dish.price * dish.count, 0)
    }
  }
})

HTML模板

<div id="app">
  <div v-for="(dish, index) in dishes" :key="dish.id" class="dish-item">
    <span>{{ dish.name }} - ¥{{ dish.price }}</span>
    <button @click="decrement(index)">-</button>
    <span>{{ dish.count }}</span>
    <button @click="increment(index)">+</button>
  </div>
  <div class="total">
    总计: ¥{{ totalPrice }}
  </div>
</div>

CSS样式

.dish-item {
  margin: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
}

.dish-item button {
  width: 30px;
  height: 30px;
  margin: 0 5px;
}

.total {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}

功能说明

  • 使用v-for指令循环渲染菜品列表
  • 每个菜品包含名称、价格和数量
  • 点击+按钮增加数量,点击-按钮减少数量
  • 计算属性totalPrice实时计算总价
  • 数量不会减少到负数以下

扩展功能

可以添加更多功能来完善点菜系统:

// 添加清空功能
methods: {
  clearAll() {
    this.dishes.forEach(dish => dish.count = 0)
  }
}

// 添加提交订单功能
methods: {
  submitOrder() {
    const selectedDishes = this.dishes.filter(dish => dish.count > 0)
    if (selectedDishes.length === 0) {
      alert('请至少选择一道菜')
      return
    }
    // 发送订单数据到服务器
    console.log('提交订单:', selectedDishes)
  }
}

标签: 加减vue
分享给朋友:

相关文章

vue实现缩放

vue实现缩放

Vue 实现缩放的方法 在 Vue 中实现缩放功能可以通过多种方式完成,以下是一些常见的方法: 使用 CSS transform 属性 通过 CSS 的 transform: scale() 属性可…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue实现ssr

vue实现ssr

Vue 实现 SSR(服务端渲染) Vue 的服务端渲染(SSR)允许在服务器端生成完整的 HTML 内容,再发送到客户端,提升首屏加载速度和 SEO 友好性。以下是实现 Vue SSR 的关键步骤和…

vue实现答辩

vue实现答辩

Vue 实现答辩系统的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装 Vue Router 管理路由,Pinia/Vuex 进行状态管理。配置 ESLint 和 Pre…

proxy实现vue

proxy实现vue

使用 Proxy 实现 Vue 响应式系统 Vue 3 的响应式系统基于 JavaScript 的 Proxy API,通过代理对象实现对属性的拦截和依赖追踪。以下是实现的核心逻辑: 创建响…

vue实现列表

vue实现列表

Vue 实现列表的方法 在 Vue 中实现列表渲染通常使用 v-for 指令,可以动态生成多个元素。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 遍历数组,生成列表项。v-for 需要…