search

Home  >  Q&A  >  body text

How to create sorting functionality in VueJS?

I'm trying to create a sort function in my VueJS code. It has the following fields: Price: low to high , Price: high to low .

So, this is my template:

<div name="divSortBy">
        <span>
          Sort by:
        </span>
        <select v-model="sort" name="selectSortBy">
          <option
            v-for="item in sortedList"
            :key="item.id"
            name="selectOptionsSortBy"
            :value="item"
            @click="sortBy"
            v-text="item.title"
          ></option>
        </select>
      </div>

This is in data() { return {} }:

sortByItems: [
    {
      id: 1,
      title: 'Price: Low to High',
      sort: 1
    },
    {
      id: 2,
      title: 'Price: High to Low',
      sort: 2
    }
  ],
  sort: null
productsList: [],

This is compulated:

computed: {
sortedList() {
  // FILTER HERE
  if (this.sort) {
    if (this.sort.id === '1') {
      console.log(this.sort.title) // console.log for tests
      this.productsList.sort(function(a, b) {
        return a.price - b.price
      })
    } else if (this.sort.id === '2') {
      console.log(this.sort.title)
    }
  }

  return this.sortByItems
}

As you can see, I'm trying to sort it by this function, but it doesn't work:

this.productsList.sort(function(a, b) {
        return a.price - b.price
      }

By the way, productsList:[] is a list of objects, therefore, I need to sort it by the price field and then display the sorted products on the page.

Thanks!

P粉438918323P粉438918323321 days ago358

reply all(1)I'll reply

  • P粉738248522

    P粉7382485222024-02-22 10:36:07

    You can customize the sorting algorithm by passing a comparator function

    Demo

    if (this.sort.id === "1") {
      return [...this.productsList].sort(function (a, b) {
        return a.price - b.price;
      });
    } else if (this.sort.id === "2") {
       return [...this.productsList].sort(function (a, b) {
        return b.price - a.price;
      });
    }

    reply
    0
  • Cancelreply