当前位置:首页 > VUE

vue实现点菜加减

2026-02-18 16:58:36VUE

实现点菜加减功能

在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实时计算总价
  • 数量不会减少到负数以下

扩展功能

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

vue实现点菜加减

// 添加清空功能
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中实现文章锚点定位可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML锚点 通过HTML的id属性和<a>标签的href属性实现锚点跳转。在Vu…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue实现布局

vue实现布局

Vue 实现布局方法 Vue 提供了多种方式实现页面布局,可以通过组件化、CSS 框架或自定义样式完成。以下是几种常见方法: 使用 CSS Flexbox 或 Grid 通过 Vue 单文件组件结合…

vue实现数据

vue实现数据

Vue 实现数据绑定的方法 Vue.js 提供了多种方式实现数据绑定,包括双向绑定、单向绑定以及动态数据绑定。以下是几种常见的实现方式: 双向数据绑定(v-model) 双向数据绑定通常用于表单元素…

vue实现修改

vue实现修改

Vue 实现修改功能的方法 在 Vue 中实现修改功能通常涉及表单绑定、状态管理和 API 调用。以下是几种常见实现方式: 双向数据绑定实现表单修改 使用 v-model 指令绑定表单元素与组件数据…

前端vue实现概率

前端vue实现概率

Vue实现概率功能的方法 在Vue中实现概率功能通常涉及随机数生成和概率计算。以下是几种常见实现方式: 基础概率实现 使用Math.random()生成0到1之间的随机数,与设定概率比较:…