[Vuejs]-Vue.js table sorting (HTML & Buefy)

0๐Ÿ‘

โœ…

I actually solved my own question myself but it took some time.

The easiest way might be emitting the click in element like this (the place with normal HTML table, child component):

<template>
  <table>
    <tr>
      <th @click="$emit('sort', {column: 'Name', isAsc: !isAsc})">Name</th>
      <th> ... </th>
    </tr>
  </table>
</template>
props: {
  isAsc: Boolean,
  sortedBy: String
}

And something like this would be inserted in the parent component:

<child-component-name @sort="sortTable" :sortedBy="sortedBy" :isAsc="isAsc" v-if="yourTableSummary"> ... </child-component-name>
components: {
  'child-component-name': NameOfYourComponent
},

data() {
    return {
        isAsc: true,
        sortedBy: 'Name'
        yourTableSummary: {}
    }
},

methods: {
    sortTable({column, isAsc}) {
        // Set isAsc to default if sorted column changes
        if (column != this.sortedBy) {
            isAsc = true
        }

        let sortedList = []
        if (isAsc) {
            sortedList =
                this.yourTableSummary.Rows.sort((a, b) => {
                    return a[column].localeCompare(b[column])
                })
        } else {
            sortedList =
                this.yourTableSummary.Rows.sort((a, b) => {
                    return (a[column].localeCompare(b[column]) * -1 )
                })
        }

        this.yourTableSummary.Rows = [...sortedList]
        this.sortedBy = column
        this.isAsc = isAsc
    },
}

Leave a comment