How to create sorting functionality in VueJS?
P粉438918323
P粉438918323 2024-02-21 11:49:53
0
1
327

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粉438918323
P粉438918323

reply all(1)
P粉738248522

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;
  });
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template