Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 2 table sorting

I am trying to create a sortable table by using Vue.js 2. I have already generated a table and now just wondering how to sort this table.

Please see below my code:

        <thead>
        <tr>
            <th class="table-header">Metric</th>
            <th class="table-header" v-for="metric in metricList"><a href="#">{{metric}}</a></th>
        </tr>
    </thead>
    <tbody>
        <template v-for="item in metricItem">
            <tr>
                <td class="table-cell" style="font-weight:bold"> {{ item }}</td>
                <template v-for="metric in metricList">
                    <td class="table-cell">
                        {{getData[item][metric]}}
                    </td>
                </template>
            </tr>
        </template>
    </tbody>

<script>
import { mapGetters, mapMutations } from 'vuex';
export default {
    name: 'scores',

    data(){
        return {
            metricList : ["Current", "Min", "Avg", "Max"],

            metricItem : [
                'Happiness Score',
                'Sadness Score'
            ]
        }
    },


    computed: {
        ...mapGetters ([
            'getData', //getter to get data
        ])
    }
}
</script>

and the data set is something like this:

getData {

    Happiness Score {

        Min : 62,
        Max : 154,
        Avg : 103
        Current : 100

    },

    Sadness Score {

        Min : 66,
        Max : 54,
        Avg : 73
        Current : 45

    },

}

I am trying to create a sortable table by using Vue js 2. I have already generated a table, and now just wondering how to sort this table.

like image 207
Gary Fan Avatar asked Jun 04 '26 13:06

Gary Fan


1 Answers

If you want to sort the table when clicking the metric showed in the header, add a sorting method and bind it by using @click.

// ...
methods: {
  sort(metric) {
    this.metricItem = this.metricItem.sort((item1, item2) => {
      // change `>=` to `<` if you want to sort in descending order
      return this.getData[item1][metric] >= this.getData[item2][metric];
    });
  },
}
// ...

See the full demo here.

like image 192
choasia Avatar answered Jun 07 '26 09:06

choasia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!