[Vuejs]-How to change Data value only for a specific block with Vue.js?

-1👍

Try this one?

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

  methods: {
    increment(i) {
      let counterdata = this.counter[i];
      this.counter = { ...this.counter, [i]: counterdata+1};
    },
    decrement(i) {
      let counterdata = this.counter[i];
      this.counter = { ...this.counter, [i]: counterdata-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 v-for="i in 4" class="firs-comp">
    <button v-on:click="increment(i)">Add {{ i }}</button>
    <p>The button above has been clicked {{ counter[i] }} times.</p>
    <button v-on:click="decrement(i)">remove {{ i }}</button>
  </div>

</div>

-2👍

use arrays for the counter like so

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>

and if you need to use it with v-for you can do something like

<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 usage of this.counter.splice(i, 1, this.counter[i]+1) is to tell vue that this value changed, otherwise it wouldn’t know and wouldn’t display the changes (even though it’d change if you console.log the value)

Leave a comment