Is it possible to do Computed Properties for an array of objects?

2

Is it possible to do something like this ?, and how would it be done?

HTML

<div id="example" v-for="item in items">
  a={{ item.a }}, b={{ item.b }}
</div>

JS

var vm = new Vue({
  el: '#example',
  data:{items: [
     {a: 1},
     {a: 3},
   ],
  },
  computed: {
    items.b: function () {
      return this.items.a + 1
    }
  }
})
    
asked by Ernesto Hernández 28.08.2016 в 17:33
source

1 answer

3

One solution is to create another computed array and use that other array as your source for the view. Something like that

var vm = new Vue({
  el: '#example',
  data: {
    items: [{
      a: 1
    }, {
      a: 3
    }, {
      a: 5
    }],
  },
  computed: {
    itemsComputados: function() {
      return this.items.map(function(i) {
        return {
          a: i.a,
          b: i.a + 1
        }
      });
    }
  }
})
<script src="http://vuejs.org/js/vue.min.js"></script>
<div id="example" v-for="item in itemsComputados">
  a={{ item.a }}, b={{ item.b }}
</div>

Instead of v-for="ítems in items" I'm using v-for="ítems in itemsComputados" and in this way I can access the modified individual items instead of your original arrangement.

    
answered by 29.08.2016 / 16:07
source