Add values from a column (array) - Vue.js?

Asked

Viewed 222 times

0

I would like to know how to add up the values of a array to appear on the screen. Example has a column with gross value, which contains the gross value of each component, wanted to add these values.

That one columns, imports from a template data-table the gross value data

data() {
    return {
      columns: [  name: "valorbruto",
          label: "Valor Bruto",
          field: "valorbruto",
          type: "money",
          width: 4,
          dontbreak: true,
          sortable: true
      },]

I tried that code and then interpolate, but it didn’t work.

Computed: {
    Valores(){
      const ValorBrutoTotal = valorbruto
       .reduce((acc, current) => 
        acc + current, 0);
      return ValorBrutoTotal;

      console.log(ValorBrutoTotal)
    }
  },
  • Try to improve your example. You want to add up all properties width? I ask this because it is the only number present in the object you put in the question.

  • want to add the raw value, the raw value comes from the backend bringing values, I wonder how I do a computed to put on screen the overall result of the raw value array

1 answer

0

I don’t quite understand your code, I’m going to propose here a way to sum up the items of a array by a certain key and also add new items in that array. Was used computed to create a function that sums the values of a given name key width, as in this example:

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

new Vue({
  el: '#editor',
  data: {
    value: 10,
    items: [
      { width: 100 },
      { width: 200 },
      { width: 150 },
      { width: 111 },
    ]
  },
  methods: {
    onSubmit() {
      const width = parseInt(this.value);
      if (width) {
        this.items = [...this.items, { width }];
        this.value = 0;
      }
    }
  },
  computed: {
    total() {
      return this.items.reduce((a, b) => {
        return a + b.width;
      }, 0);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="editor">
    <form v-on:submit.prevent="onSubmit">
      <input type="number" v-model="value" /> 
      <button>Incluir</button>
    </form>
    <ul>
      <li v-for="item in items">{{item.width}}</li>
    </ul>
    <hr />
    <div>
      <i>Somatória:</i> <b>{{total}}</b>
    </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.