[Vuejs]-Vue JS 2: Bind computed property to data attribute

0👍

Here are a few approaches: Binding to a method, binding to a computed property, and binding to a data property that is saved during the computed property call:

  <table id="table">
     <thead>
        <tr>
           <td>Value 1</td>
           <td>Value 2</td>
           <td>Sum</td>
           <td>Sum</td>
           <td>Sum</td>
        </tr>
     </thead>
     <tbody>
        <tr v-for="(item, index) in items">
           <td><input type="number" v-model="item.value1"></td>
           <td><input type="number" v-model="item.value2"></td>
           <td> {{ sum(item) }} </td><!-- method -->
           <td> {{ sums[index] }}</td><!-- computed -->
           <td> {{ item.valuesum }}</td><!-- data property via computed -->
        </tr>
     </tbody>
  </table>

The script:

var vm = new Vue({
   el: "#table",
   data: function () {
      return {
         items: [
            {
               value1: 10, 
               value2: 10,
               valuesum: 0
            },{
               value1: 10, 
               value2: 100,
               valuesum: 0,
            }
         ]
      }
   },

   computed: {
      sums: function () {
         var val = [];
         for (var index in this.items) {
            var sum = this.sum(this.items[index]);
            val.push(sum);

            // Update the local data if you want
            this.items[index].valuesum = sum;
         }
         return val;
      }
   },

   methods: {
      sum: function (item) {
         // Alternate, if you take valuesum out:
         // for (var prop in item) {
         //    val += parseInt(item[prop]);
         // }
         return parseInt(item.value1) + parseInt(item.value2);
      }
   }
});

Is that the sort of thing you’re looking for?

👤exclsr

Leave a comment