The action of adding an item to the cart will result in all counters

I am facing an issue where the counters of all options in the cart increase simultaneously when I add an option. I initially attempted to solve this using Vuex, but my lack of experience led me to take a simpler approach. How can I prevent all option counters from increasing when adding just one?

(I have included an example of the code to make it easier to understand.)

<template>
    <div>
         <div v-for="optionTests in ArrayOption" :key="optionTests.id">
            <p>{{ optionTests.id}}</p>
            <p>{{ optionTests.name}}</p>
            <p>{{ optionTests.description}}</p>
            <button  @click="testCount -= 1" :disabled="testCount < 1">-</button>
            <p>{{ testCount }}</p>
            <button @click="testCount += 1" :disabled="testCount > 0">+</button>
        </div>
    </div> 
</template>
 
<script>
import axios from 'axios'
 
export default {
    data(){
        return{
            ArrayOption:[
                {
                    id:1,
                    name: 'option1'
                    description: 'This is option 1, add me to the cart!'
                },
                {
                    id:2,
                    name: 'option2'
                    description: 'This is option 2, add me to the cart!'
                },
                {
                    id:3,
                    name: 'option3'
                    description: 'This is option 3, add me to the cart!'
                },
                {
                    id:4,
                    name: 'option4'
                    description: 'This is option 4, add me to the cart!'
                }
            ],
            testCount:0,
        }
    }
}

https://i.sstatic.net/e22J5.jpg

Answer №1

What is happening here is that each option in the array is being rendered as a unique card, but all the counters are linked to the same variable in the data.

As a result, when you update one counter, all the counters update to reflect the new total because they are essentially showing the same number underneath the surface, even though they are displayed in different locations.

To fix this issue, you need to store the option counts separately so that each count can be accessed and manipulated independently.


One approach to address this is as follows:

Instead of directly displaying and manipulating testCount, you can store each option count as a key in a counter object. This allows each count to be incremented or decremented individually:

testCounter: { 
  "option1": 0, 
  "option2": 0,
  "option3": 0,
  "option4": 0 
}

Here is a demonstration showcasing this concept!

Please note that a special Vue instance method, vm.$set(), is required to make the individual counters reactive. Vue cannot track dynamically created properties in an object, so we must explicitly use

vm.$set([object], [key name], [initial value])
to add a new key.

new Vue({
  el: '#app',
  data() {
    return {
      arrayOption: [{
          id: 1,
          name: 'option1',
          description: 'je suis l option 1 ajoute moi au panier'
        },
        {
          id: 2,
          name: 'option2',
          description: 'je suis l option 2 ajoute moi au panier'
        },
        {
          id: 3,
          name: 'option3',
          description: 'je suis l option 3 ajoute moi au panier'
        },
        {
          id: 4,
          name: 'option4',
          description: 'je suis l option 4 ajoute moi au panier'
        }
      ],
      testCount: {},
    }
  },
  created() {
    // This step is crucial - using this.$set ensures the counter properties are reactive
    // which enables DOM updates when a counter is clicked
    this.arrayOption.forEach(op => this.$set(this.testCount, op.name, 0));
  },
});
.card {
  background: #bbc0c4;
  border: solid;
  padding: 5px;
  margin: 5px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: space-around;
  justify-content: space-around;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div>
    <p>Values: {{ testCount }}</p>
    <div v-for="optionTest in arrayOption" :key="optionTest.id" class="card">
      <p>{{ optionTest.id }}</p>
      <p>{{ optionTest.name }}</p>
      <p>{{ optionTest.description }}</p>
      <button @click="testCount[optionTest.name] -= 1" :disabled="testCount[optionTest.name] < 1">-</button>
      <p>{{ testCount[optionTest.name] }}</p>
      <button @click="testCount[optionTest.name] += 1" :disabled="testCount[optionTest.name] > 0">+</button>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for Resolving the Issue of Number Separator in Chrome

Having an issue with the number's separator in </v-text-field>, I prefer it to be a dot like in Firefox, not a comma like in Chrome FireFox Example: https://i.sstatic.net/msgfg.jpg Chrome Example: https://i.sstatic.net/Hx0kr.jpg Template: & ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

What can Yeoman do with php files?

How can I set up Yeoman (latest version: v0.9.6) to serve php files? I came across this post but couldn't get it to work. I installed https://github.com/fgnass/gateway, https://github.com/fgnass/tamper and made the necessary updates to Yeoman accor ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Using AngularJS to handle error validation for dropdowns and select elements that will redirect using the ng

Currently, I am utilizing angularjs's ng-href along with a select HTML element containing ng-model. The ng-href is being used to link to the "selectedItem" from ng-model. However, I have encountered difficulty in validating or displaying an error mess ...

How do I fix TypeError: req.flash is not a valid function?

While working with user registration on a website, validation is implemented using mongoose models and an attempt is made to use Flash to display error messages in the form. However, in my Node.js app, an error is occurring: TypeError: req.flash is not ...

Selenium-Web Driver encounters an issue with reading the 'filter' property as undefined

Recently, I started working with Selenium and encountered an issue while trying to wait for a specific element to load. The error message that popped up was: (node:8472) UnhandledPromiseRejectionWarning: NoSuchElementError: no such element: Unable to ...

Using VueJS to switch classes on multiple cards

There is a page with multiple cards, each containing its own set of status radio buttons: ok, missing, error. The goal is to be able to change the status of individual cards without affecting others. A method was created to update the class on the @change ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

A step-by-step guide on activating dark mode for the markdown-it-vue plugin while incorporating Vuetify styling

I'm looking to display some documentation in my Vue application. The documentation is in markdown format, so I have already integrated the markdown-it-vue plugin. However, I've run into an issue where the plugin doesn't support vuetify dark ...

How can I stop a table from resizing in Tailwind CSS?

So, I have created this table <table class="table-fixed border-separate border border-green-800"> <thead class="bg-indigo-800 border-b-2 border-indigo-200 w-full"> <tr> <th ...

How to ensure that the select option is always at the top of the select dropdown list in a React.js application

Within the select dropdown menu, I have included a default option value of "--select--". As it currently appears at the bottom of the list, I would like it to be displayed at the top instead. Can someone please assist me in achieving this? In the sandbox, ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned. function obtainName(idName, idTy ...

After closing, the position of the qtip2 is being altered

I've successfully integrated the qtip2 with fullcalendar jQuery plugin, which are both amazing tools. However, I'm encountering an issue with the positioning of the qtip. Here's the code snippet I'm using: $(window).load(function() { ...

Creating a dynamic user interface with HTML and JavaScript to display user input on the screen

I'm currently working on creating an input box that allows users to type text, which will then appear on the screen when submitted. I feel like I'm close to getting it right, but there's a problem - the text flashes on the screen briefly bef ...

Can you explain the functionality of this JavaScript registration code?

I am working on an ajax/jquery 1.3.2 based sign up form and I am looking to gain a deeper understanding of how to incorporate jquery into my projects by analyzing the code line by line. Could someone provide a detailed explanation of this code and break d ...

A promise is given when a value triggers a function

Having a problem with my code in the second function. When I log inside the function, it works fine. But when I assign a variable and call the function, it returns a pending promise instead of true or false. const mongoose = require('mongoose') c ...