Tips for updating the data value of a specific block using Vue.js

I am looking to develop a basic Vue.js application. Within this app, I have multiple counter blocks that are rendered using the v-for directive. In my data object, I initialize a 'counter: 0' instance. My goal is to increment and decrement only one specific block when a button is clicked. However, I am currently facing an issue where both block values change simultaneously upon a button click event. How can I go about resolving this problem?

let example1 = new Vue({
  el: '#example-1',
  data: {
    counter: 0
  },
  
  methods:{
         increment(){
            this.counter++
        },
        decrement(){
            this.counter--
        }
  }
})
.firs-comp{
 border:2px solid red;
 margin-top:10px;
 margin-bottom:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="example-1">
  <div class="firs-comp">
    <button v-on:click="increment">Add 1</button>
     <p>The button above has been clicked {{ counter }} times.</p>
     <button v-on:click="decrement">Remove 1</button>
  </div>
   <div class="firs-comp">
    <button v-on:click="increment">Add 1</button>
     <p>The button above has been clicked {{ counter }} times.</p>
     <button v-on:click="decrement">Remove 1</button>
  </div>
</div>

Answer №1

Why not give this a shot?

let example = new Vue({
  el: '#example-1',
  data: {
    counter: {
      1 : 0,
      2 : 0
    }
  },

  methods: {
    increment(id) {
      let countData = this.counter[id];
      this.counter = { ...this.counter, [id]: countData+1};
    },
    decrement(id) {
      let countData = this.counter[id];
      this.counter = { ...this.counter, [id]: countData-1};
    }
  }
})
.sample-component {
  border: 2px solid blue;
  margin-top: 10px;
  margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="example-1">

  <div v-for="id in 4" class="sample-component">
    <button v-on:click="increment(id)">Add {{ id }}</button>
    <p>The button above has been clicked {{ counter[id] }} times.</p>
    <button v-on:click="decrement(id)">Remove {{ id }}</button>
  </div>

</div>

Answer №2

Here's a simple way to use arrays for counting:

var example1 = new Vue({
  el: '#example-1',
  data: {
    counter: new Array(2).fill(0)
  },
  
  methods:{
         increment(i){
            this.counter.splice(i, 1, this.counter[i]+1)
        },
        decrement(i){
            this.counter.splice(i, 1, this.counter[i]-1)
        },

  }
})
.firs-comp{
 border:2px solid red;
 margin-top:10px;
 margin-bottom:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="example-1">
  <div class="firs-comp">
    <button @click="increment(0)">Add 1</button>
     <p>The button above has been clicked {{ counter[0] }} times.</p>
     <button @click="decrement(0)">remove 1</button>
  </div>
   <div class="firs-comp">
    <button @click="increment(1)">Add 1</button>
     <p>The button above has been clicked {{ counter[1] }} times.</p>
     <button @click="decrement(1)">remove 1</button>
  </div>
</div>

If you want to use v-for, you can try something like this:

<div id="example-1">
  <div v-for="(_, i) in counter" class="firs-comp">
    <button @click="increment(i)">Add 1</button>
    <p>The button above has been clicked {{ counter[i] }} times.</p>
    <button @click="decrement(i)">remove 1</button>
  </div>
</div>

The reason for using

this.counter.splice(i, 1, this.counter[i]+1)
is to notify Vue of the change so it can update accordingly. Otherwise, even if the value changes, Vue wouldn't know to display it (even though it would reflect in console.log).

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

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

What could be the reason for the malfunctioning of the Angular options tracking by ID feature?

I seem to be facing an issue with my code: There is an object that holds the id of an item, along with an array containing these items. I require a 'select' element to display the currently selected item and allow for changing the selection. Th ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

The button's color cannot be modified due to a malfunctioning event script that is not

Seeking an explanation for why my current implementation isn't working. I'm attempting to create a quiz with a multiple choice section where the correct answer turns green when clicked, and incorrect answers turn red. Despite validating the code ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...

Using `require(variable)` is not functional in next-js environment

I'm attempting to display an image using the next-optimised-images module. When I try to include images like this: <img src={require(c.logo)} alt={c.title} /> I encounter the following error: https://i.stack.imgur.com/Jtqh9.png However, when ...

User information in the realm of website creation

Can someone provide insight on where user data such as photos, videos, and posts is stored? I doubt it is saved in an SQL database or any similar system. ...

I am looking to obtain assistance through denomongo for guidance

The deno-mongo guide page on GitHub is no longer functional. You can find the page here: 'https://github.com/manyuanrong/deno_mongo' I am struggling to understand how to use the plugin and get it up and running. Following the example in the "Re ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Having trouble retrieving XSRF-TOKEN from cookie in Next.js (React.js)?

When working with Next.js and Laravel 8 backend, I encountered an issue where I couldn't set the XSRF-TOKEN generated by Laravel on my fetch request for login. Despite being able to see the token in the inspect element > application tab > cookie ...

Using Vue 3 to dynamically render a component from a string

I have a question about the ValidateCheckboxes component I am working with. ValidateCheckboxes is a specialized list of checkboxes that I pass to the component as props. Here's how it typically looks: view image here view image here I use v-for to dis ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Encountering 404 Errors with CSS and JS files in Nuxt3 while deploying to the test channel of Firebase Hosting

I've been facing an issue while trying to deploy a Nuxt3 project using Github Actions to Firebase Hosting. The workflow script runs smoothly and the app builds without any errors. However, when accessing the testing channel URL, several CSS and JS fil ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...