3

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks mate, it working fine. However, what if I want to make it descending order when I make a second click ?
Check the current order when clicking or mark the order in a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.