You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中数组元素增查及购物车商品添加功能代码修复咨询

修复Vue商城购物车添加商品功能的方案

问题分析

  • 按钮位置错误:当前按钮在v-for循环外,无法关联具体商品,点击时无法确定要添加的目标商品
  • 添加逻辑错误:this.items是商品数组,不存在id属性,this.cart.push(this.items.id)会将undefined加入购物车,导致购物车无内容展示

修复后的完整代码

shop.vue

<template>
  <div class="shop">
    <h1>shop</h1>
    <!-- 将按钮放入商品循环内,绑定当前商品 -->
    <div class="products" v-for="item in items" :key="item.id">
      {{ item.name }} - {{ item.price }}
      <button @click="addToCart(item)">Add to Cart</button>
    </div>
  </div>
  <div class="cart">
    <h1>cart</h1>
    <div class="cartitems" v-for="item in cart" :key="item.id">
      {{ item.name }} {{ item.price }}
    </div>
  </div>
</template>

<script>
import Products from "../db.json"
export default {
  name: "shop",
  data() {
    return {
      items: Products,
      cart: []
    }
  },
  methods: {
    addToCart(product) {
      // 直接将传入的商品对象加入购物车
      this.cart.push(product)
      
      // 可选:添加去重逻辑,避免重复加入同一商品
      // const isExist = this.cart.some(item => item.id === product.id)
      // if (!isExist) {
      //   this.cart.push(product)
      // }
    }
  }
}
</script>

db.json(保持原内容不变)

[
  {
    "id": 1,
    "name": "iphone",
    "price": 2000
  },
  {
    "id": 2,
    "name": "galaxy",
    "price": 3000
  }
]

修复效果

每个商品旁会显示独立的添加按钮,点击后对应商品会实时加入购物车并在购物车区域展示。若需要避免重复添加同一商品,可启用代码中注释的去重逻辑。

内容的提问来源于stack exchange,提问作者kikidoyouloveme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:50:16