0

I created a select element in HTML and want to create an option for a user to sort a table by select element option values.

The data I want to sort (there will be many objects):

enter image description here

I am watching a select element which has a v-model value of sort:

  watch: {
  search: function (val) {
    if (val.length === 0) return this.filtered = this.affiliates;

    this.filtered = this.affiliates.filter(function (cont) {
      return cont.shop_name.toLowerCase().indexOf(val.toLowerCase()) >= 0 || cont.app_name.toLowerCase().indexOf(val.toLowerCase()) >= 0;
    });
  },
  sort: function (val) {
    console.log(this.filtered);
  },

How could I sort objects by watched value?

Data is stored in this.filtered

I want to sort by these values:

 <select v-model="sort">
          <option value="date_installed">Latest</option>
          <option value="status">Status</option>
          <option value="share">Share</option>
        </select>
ViktorasssIT
  • 377
  • 7
  • 23

1 Answers1

0

While you can make it work with a watch, this seems like a better fit for computed

The sort function takes a compare function as an argument, you can dynamically compare the objects based on sort preference by passing it as a key using bracket notation for accessor.

<template>
    <div>
        <select v-model="sortBy">
            <option value="date_installed">Latest</option>
            <option value="status">Status</option>
            <option value="share">Share</option>
        </select>
        <ul>
            <li v-for="item in filtered" :key="item.id">{{ item.app_name}}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            sortBy: [],
            affiliates: [
                //...
            ]
        }
    },
    computed: {
        filtered() {
            if (val.length === 0) return this.affiliates;
            return this.affiliates.sort( (a,b) => {
                return a[this.sortBy] - b[this.sortBy]
            });
        }
    },
}
</script>
Daniel
  • 34,125
  • 17
  • 102
  • 150