代码之家  ›  专栏  ›  技术社区  ›  Elisaniza

购物车问题,添加产品,在vuejs

  •  0
  • Elisaniza  · 技术社区  · 3 年前

    我的购物车有一个问题:当我想向购物车添加产品时,我的功能会为每个可用产品添加一个产品。(我希望这一点足够清楚,因为英语不是我的第一语言)

            <h3>Product list</h3>
            <ul>
                <li>
                    {{plants.productName}} : {{plants.quantity}}
                </li>
            </ul>
        </div>
        <br><br>    
        
        <div>
            <h3>Shopping list:</h3> 
            <ul>
            <li v-for="plant in plantList">
                {{plant.productName}} : {{stock}}
                <button @click="addPlant">Add {{plant.productName}}</button> 
                <!--<span v-if="plant.quantity === 0">No stock</span>
               -->
                
            </li>
          </ul> 
        </div>
            
    </div>
        <script>
        const app=new Vue({
            el: '#app', 
            data: {
                
                stock: 0,
                plantList:[
                    {productName: 'flowers', quantity: 5},
                    {productName: 'cactus', quantity: 3},
                    {productName: 'trees', quantity: 6},
               ]
            }, 
            
            methods: {
                addPlant(){
               
                this.stock += 1;
                
                }
                
        })
    
    </script>
    

    我只想在点击按钮时添加一个产品

    0 回复  |  直到 3 年前
        1
  •  0
  •   Luis de Brito    3 年前

    当将商品添加到购物车时,您需要某种方式来指定特定商品的数量,按照它的实现方式,您添加了一个数量,但没有告知哪个商品。 要解决这个问题,请创建一个数组作为购物车,并在购物车中添加与产品相关的数量。

    此外,当显示每个商品的数量时,您必须根据购物车上的商品标识来显示它(在下面的示例中,我使用名称作为标识)。这就是问题所在,你表现出了同样的价值( stock )到所有项目。

    以下是工作的方式。

    <template>
      <div>
        <h1>Product list</h1>
    
        <div>
            <h3>Shopping list:</h3> 
            <ul>
              <li v-for="plant in plantList">
                  {{ plant.productName }} : {{ cart[plant.productName] }}
                  <button @click="addPlant(plant)">Add {{plant.productName}}</button>
              </li>
            </ul> 
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data: () => ({
        cart: [], // holds the referente to each item and quantity
        plantList:[
            {productName: 'flowers', quantity: 5},
            {productName: 'cactus', quantity: 3},
            {productName: 'trees', quantity: 6},
       ]
      }),
    
      methods: {
        addPlant(plant){
          // if the item is in the cart, add +1 to item
          if(this.cart[plant.productName]) {
            this.cart[plant.productName] += 1
            return
          }
    
          // if the item is not in the cart, add it with 1 as quantity
          this.cart[plant.productName] = 1
        }
      }
    }
    </script>
    

    Live demo here