[Vuejs]-Customising column sort order in v-data-table

0👍

   formatMember(){
  let newMembers = this.auditResults.slice();
  newMembers.map((el) => (el.codeid = this.getCodeValue(el.codeid)));
  return newMembers;
}

I got it. So no need to manual sort the data and we can change the property of our data model in computed component. This works for me 100%.

In my vuetify table instead of auditResult I changed it to formatMember. Meaning the table is using the computed method to get the array object.

    <v-data-table
    :items="formatMember"
    :headers="headers"
    class="searchable sortable"
  >

Hope this will help others in future.

Thanks.

👤Lep

3👍

You can give a v-data-table your own function to use to compare rows by passing sort option in header definition

In headers:

headers: [
    {
        text: 'Code',
        value: 'codeid',
        sort: function(a, b) {
            // implement custom compare function here
        },
    },
],

Function passed to sort should implement same "contract" as used in Array.prototype.sort

  1. return 0 if items are equal
  2. return -1 if a < b (a comes first)
  3. return +1 if a > b (b comes first)

Some notes:

  1. this.auditResults.codeid = codeFound.code;auditResults is an array so you are adding new property to your array instance, not changing value of codeid in your object inside the array
  2. I don’t recommend doing such thing anyway. Your function is called for every row every time the template is re-rendering so you will end up with "Code not found" value in every row eventually
  3. You should probably add new property (with value looked up by your function) into your data objects once (beware of Vue’s Change Detection Caveats) after you receive your data from API instead of looking up the value every time. Then you will not need any custom sorting or custom rendering logic…

Leave a comment