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!
You can customize the sorting algorithm by passing a comparator function
Demo