[Vuejs]-Should I be using a computed property here?

0👍

Computed values never should mutate data.

I would suggest that your computed value return a new array with the difference in it.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {

    items: [{
        a: 10,
        b: 4
      },
      {
        a: 443,
        b: 23
      }
    ]

  },
  computed: {
    items_with_difference() {
      return this.items.map((i) => ({
        ...i,
        difference: i.a - i.b
      }));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <thead>
      <th>
        A
      </th>
      <th>
        B
      </th>
      <th>
        Difference
      </th>
    </thead>
    <tbody>
      <tr v-for="(item, idx) in items_with_difference" :key="idx">
        <td>
          {{item.a}}
        </td>
        <td>
          {{item.b}}
        </td>
        <td>
          {{item.difference}}
        </td>
      </tr>
    </tbody>
  </table>
</div>

Leave a comment