LorenzoBerti
LorenzoBerti

Reputation: 6974

change value and render object in v-for Vuejs

I have a jsonArray and in my template component have v-for like:

<div v-for="obj in data.objects" :key="obj.id">
   <strong>Quota:</strong>
      <span>{{obj.quota}}</span>
</div>

And I have a function in my component that should change value of obj.quota after click button, like:

refreshValue: function(element){
   this.data.objects.forEach((e, i) => {
      if (e.id == element.id) {
         this.data.objects[i].quota = e.fractionNuminator /e.fractionDenominator;
      }
   });
}

But the problem is the object doesn't refresh and not render new value of object.

What I'm wrong? How I should change value in v-for?

Thankyou!

Upvotes: 0

Views: 8313

Answers (1)

MattDionis
MattDionis

Reputation: 3616

I was able to get this working in this jsFiddle.

<div id="vue-instance">
  <div v-for="obj in objects">
    <strong>Quota:</strong>
    <span>{{obj.quota}}</span>
    <button @click="refreshValue(obj)">Refresh!</button>
  </div>
</div>

var vm = new Vue({
  el: '#vue-instance',
  data: {
    objects: [
      {id: 1, quota: 100, numerator: 1, denominator: 3},
      {id: 2, quota: 120, numerator: 2, denominator: 5},
      {id: 3, quota: 75, numerator: 5, denominator: 6},
      {id: 4, quota: 350, numerator: 3, denominator: 8}
    ]
  },
  methods: {
    refreshValue: function(element) {
      this.objects.forEach((e, i) => {
        if (e.id == element.id) {
          this.objects[i].quota = e.numerator /e.denominator;
        }
      });
    }
  }
})

Upvotes: 2

Related Questions