I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High
, Price: High to Low
.
Here 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 inside data() { return {} }
:
sortByItems: [
{
id: 1,
title: 'Price: Low to High',
sort: 1
},
{
id: 2,
title: 'Price: High to Low',
sort: 2
}
],
sort: null
productsList: [],
And here is the computed
section:
computed: {
sortedList() {
// FILTER HERE
if (this.sort) {
if (this.sort.id === '1') {
console.log(this.sort.title) // console log for testing purposes
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
}
Although I attempted to use the following sorting function, it doesn't seem to be working as expected:
this.productsList.sort(function(a, b) {
return a.price - b.price
}
Just to clarify, productsList: []
contains a list of objects and I need to sort them based on the price
field before displaying them on the page.
Thank you!