当前位置:首页 > VUE

vue实现点菜加减

2026-02-18 16:58:36VUE

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 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

实现 vue ssr

实现 vue ssr

Vue SSR 实现方法 Vue SSR(Server-Side Rendering)通过服务器端渲染 Vue 应用,提升首屏加载速度和 SEO 友好性。以下是核心实现方法: 基础配置 安装必要依赖…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <template&…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue 实现视频

vue 实现视频

Vue 实现视频播放功能 使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法: 使用 HTML5…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装 sc…