我正在尝试在我的 VueJS 代码中创建排序函数。它具有以下字段:Price:从低到高,Price:从高到低。
所以,这是我的 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>
这在 data() { return {} }:
sortByItems: [
{
id: 1,
title: 'Price: Low to High',
sort: 1
},
{
id: 2,
title: 'Price: High to Low',
sort: 2
}
],
sort: null
productsList: [],
这是 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
}
正如你所看到的,我试图通过这个函数对其进行排序,但它不起作用:
this.productsList.sort(function(a, b) {
return a.price - b.price
}
顺便说一句,productsList:[]是对象列表,因此,我需要按price字段对其进行排序,然后在页面上显示排序后的产品。
谢谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以通过传递比较器函数来自定义排序算法
演示
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; }); }