Search code examples
sumvuetify.jsv-data-table

Totaling a Summary Line in Data Table


I hve a sumField method which totals values in a given column:

sumField (key) {
    let total = 0
    const sum = this.tableName.reduce((acc, cur) => {
        return (total += +cur[key])
    }, 0)
    return sum
}

Inside my data table I call sumField to produce a rolling total of the values in a specific column of my data table:

<template v-slot:[`body.append`]="{headers}">
    <tr class="summary">
        <td v-for="(header,i) in headers" :key="i">
          <div v-if="header.value == 'COL HEADER 1'">
          {{ sumField('COL HEADER 1') }}</div>
          <div v-else-if="header.value == 'COL HEADER 2'">
          {{ sumField('COL HEADER 2') }}</div>
        </td>
    </tr>
</template>

This is presented on screen as an additional line of the data table, and the values change depending on the filters applied to the table.

Is there a way to sum the values calculated, and show this as a rolling total value also?


Solution

  • Got a solution which I hope might provide some help to others in the future!

    Started by creating a new function:

    sumTot (col1, col2) {
        var one = col1
        var two = col2
        var tot = col1 + col2
        return tot
    }
    

    Then I called sumTot giving the arguments of the individual sumField calls:

    {{ sumTotal(sumField ('COL HEADER 1'), sumField ('COL HEADER 2')) }}
    

    That gives me a dynamically updated running total value.