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>
1
  • this link will help you, possible duplicate of that answer Commented Jun 23, 2020 at 12:45

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

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.